From alan.gauld at btinternet.com Fri Aug 1 00:16:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 Jul 2008 23:16:40 +0100 Subject: [Tutor] Mixing in and Mixing out classes in python References: <176387.51878.qm@web32803.mail.mud.yahoo.com> Message-ID: <g6tdgh$sps$1@ger.gmane.org> "Tomaz Bevec" <tomazbevec at yahoo.com> wrote > I am using the following function to mixin in classes > into specific object instances ... > Is there an analogous way to "Mixout" classes from an instance at > runtime? I'm sure it is possible but... Are you just asking out of interest? Or do you have a real world need for this? Using multiple inheritence is a non trivial aspect of OOP (albeit powerful) that is fraught with difficulty and potential side effects. Adding a mixin at run time is difficult enough, removing one would bend my brain way too far I suspect. (Many coding standards insist on limiting MI to two classes or even banning it outright as being too bug prone.) Dynamic mixins add a whole new complexity (it's somewhat akin to the FAQ here about dynamically naming variables) all you generic code has to take account of the new method introduced and any potential side-effects that may not be handled in your code. Unless your mixin classes are ultra clean and stateless in their implementation you run a risk of breaking things in ways that are almost impossible to debug. I've never come across a need for dynamic mixin additions and I'm interested in how you think you might use this. (CLOS is the only other place I've even seen this discussed and it's possible there with some under the covers work but I've never seen it used!) Curious, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Aug 1 00:31:06 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 31 Jul 2008 23:31:06 +0100 Subject: [Tutor] Memory error - how to manage large data sets? References: <20080731.062222.812.1@SELINAPNOTE> Message-ID: <g6tebk$uvk$1@ger.gmane.org> "Kepala Pening" <kepalapening at gmail.com> wrote > However, to have limit = 2, perhaps I should do > while b <= limit. > > Thanks Alan for pointing it out. No probs, forgetting to test both ends of the range is a common mistake. In fact good testing practice says that for any range of values you should test - the lowest legal value - correct result - one lower than the lowest - fails gracefully - much lower than lowest - fails gracefully - a mid range value - correct result - the highest legal value - correct value (Of course testing the "highest possible value" would be tricky in your case! :-) - one higher than the highest - fails gracefully - much higher than the legal limit - fails gracefully - an invalid value - fails gracefully (eg in your case limit = 'four') So that's at least 8 tests for every range parameter/variable in your code. Automated testing is "A Good Thing" :-) Alan G. > > ----- Original Message ----- > From: "Alan Gauld" <alan.gauld at btinternet.com> > To: tutor at python.org > Date: Thu, 31 Jul 2008 06:39:32 +0100 > Subject: Re: [Tutor] Memory error - how to manage large data sets? > >> >> "Kepala Pening" <kepalapening at gmail.com> wrote >> >> > def sumEvenFibonacci( limit ): >> > a, b = 1, 1 # don't waste with a = 0 >> > sum = 0 >> > while b < limit: >> > if b%2 == 0: sum += b >> > a, b = b, a + b >> > return sum >> > >> > print sumEvenFibonacci( 2000000 ) >> >> Does it work for limit = 2? >> >> Alan G. >> >> >> >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tomazbevec at yahoo.com Fri Aug 1 02:09:51 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Thu, 31 Jul 2008 17:09:51 -0700 (PDT) Subject: [Tutor] Mixing in and Mixing out classes in python In-Reply-To: <g6tdgh$sps$1@ger.gmane.org> Message-ID: <160626.42794.qm@web32807.mail.mud.yahoo.com> Thanks for your reply Alan, I am partially asking out of interest, but I also have a potential application. I'm working on a simulation of cellular growth patterns (basically cell instances interacting stochastically on a lattice). Anyway, there are many different cell "behaviors" that I have to simulate, and cells can potentially gain and lose these "behaviors" over the course of the simulation. It would be too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing it in (and initializing it) when necessary or when biological function is gained by the cells. In addition some of the behaviors would be too big (as in lines of code) if they were implemented in one function so splitting functionality up in my mixin class makes it conceptually easier for me. Also the behaviors sometimes need access to the internals of the cell class. After I mixin a class every method that starts with the word 'behavior.*' in that class is called when I update the simulation. All of my mixins inherit from "object" only. So far my approach is working well, but I don't have a clean way for cells to lose functionality. Hence my question about mixin out. I tried to just delete the 'behavior.*' functions with the del operator (like for an attribute) but it didn't work. I have however thought of a number of ways to work around this, and per your suggestion I think I'll just try something else, but if you have any idea on how to dynamically mix out I'd be glad to here it. Thanks, Tomaz --- On Thu, 7/31/08, Alan Gauld <alan.gauld at btinternet.com> wrote: > From: Alan Gauld <alan.gauld at btinternet.com> > Subject: Re: [Tutor] Mixing in and Mixing out classes in python > To: tutor at python.org > Date: Thursday, July 31, 2008, 3:16 PM > "Tomaz Bevec" <tomazbevec at yahoo.com> wrote > > > I am using the following function to mixin in classes > > into specific object instances ... > > > Is there an analogous way to "Mixout" > classes from an instance at > > runtime? > > I'm sure it is possible but... > > Are you just asking out of interest? > Or do you have a real world need for this? > > Using multiple inheritence is a non trivial aspect of OOP > (albeit > powerful) > that is fraught with difficulty and potential side effects. > Adding a > mixin at > run time is difficult enough, removing one would bend my > brain way too > far I suspect. (Many coding standards insist on limiting MI > to two > classes > or even banning it outright as being too bug prone.) > > Dynamic mixins add a whole new complexity (it's > somewhat akin to > the FAQ here about dynamically naming variables) all you > generic > code has to take account of the new method introduced and > any > potential side-effects that may not be handled in your > code. Unless > your mixin classes are ultra clean and stateless in their > implementation > you run a risk of breaking things in ways that are almost > impossible > to debug. > > I've never come across a need for dynamic mixin > additions and > I'm interested in how you think you might use this. > (CLOS is the only > other place I've even seen this discussed and it's > possible there > with some under the covers work but I've never seen it > used!) > > Curious, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Aug 1 02:29:12 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 Jul 2008 20:29:12 -0400 Subject: [Tutor] Mixing in and Mixing out classes in python In-Reply-To: <160626.42794.qm@web32807.mail.mud.yahoo.com> References: <g6tdgh$sps$1@ger.gmane.org> <160626.42794.qm@web32807.mail.mud.yahoo.com> Message-ID: <1c2a2c590807311729m6966b118q3b31b937eda94732@mail.gmail.com> On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec <tomazbevec at yahoo.com> wrote: > Thanks for your reply Alan, > > I am partially asking out of interest, but I also have a potential application. > > I'm working on a simulation of cellular growth patterns (basically cell instances interacting stochastically on a lattice). Anyway, there are many different cell "behaviors" that I have to simulate, and cells can potentially gain and lose these "behaviors" over the course of the simulation. It would be too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing it in (and initializing it) when necessary or when biological function is gained by the cells. Perhaps you could keep the behaviors in a dictionary? You could override __getattr__() in the cell class to look up attributes whose names start with 'behavior' in the dict. Kent From cfuller084 at thinkingplanet.net Fri Aug 1 04:57:43 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 31 Jul 2008 21:57:43 -0500 Subject: [Tutor] key/value order in dictionaries In-Reply-To: <e2f191310807310333x7c019b50r328ba619024d14ab@mail.gmail.com> References: <A0B4A6C8-999B-4E04-86B6-E6AFDFAE0A3E@gmail.com> <489178D0.4000304@timgolden.me.uk> <e2f191310807310333x7c019b50r328ba619024d14ab@mail.gmail.com> Message-ID: <200807312157.43501.cfuller084@thinkingplanet.net> On Thursday 31 July 2008 05:33, Monika Jisswel wrote: > Python dictionaries are not ordered & the order you will get when you print > a dictionary is the order that the python virtual machines thinks optimal > for that dictionary for its own internal procedures. If you need an ordered dictionary, such things exist. The implementation I use is at http://www.voidspace.org.uk/python/modules.shtml, but there may be one or two other popular ones out there. You probably shouldn't use them unless you have a specific need to. They will be a lot slower, and extra dependencies always complicates distribution. Cheers From angelayian at yahoo.com Fri Aug 1 05:16:54 2008 From: angelayian at yahoo.com (Angela Yang) Date: Thu, 31 Jul 2008 20:16:54 -0700 (PDT) Subject: [Tutor] how do I create a lists of values associated with a key? Message-ID: <279879.31091.qm@web50107.mail.re2.yahoo.com> Hi, I have a list of values for one key.? How do I specify this data structure? First tried, collection = [] collection['abby'].append('apprentice1') collection['abby'].append('apprentice2') That did not work because list index is not numeric. But for dictionaries, it is key - value pairs.? But I need key -> multiple values. Do you have some example how to specify this? Angela -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/f499e527/attachment-0001.htm> From federo at email.si Fri Aug 1 09:39:39 2008 From: federo at email.si (Federo) Date: Fri, 01 Aug 2008 09:39:39 +0200 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? Message-ID: <20080801073939.974DC8CEF6@www1.email.si> Hi .. I have to admit that Python is really surprising me. It was lucky day a few weeks ago I firts time start using Python. Lot's of things realy can be done with short learning curve. Your user guieds was best place to start! Below is problem I am unable to solve. I would appreciate your advice or even better code sample. The problem is URL authorisation. I try to approaches but no luck so far. Two problems: 1.) Being able to logon using Python code 2.) Being able to send data to a form and get back server reply ad 1.) The Two pages I try to open: Login: https://investor.firstrade.com/firstrade/login.do Main page after login: https://investor.firstrade.com/firstrade/mainmenu.do I have tried bellow code (with currect user name and password of course): >>> import urllib2 >>> password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() >>> protocol = 'https://' >>> username = 'user' >>> password = 'pass' >>> top_level_url = "investor.firstrade.com/firstrade/login.do" >>> password_mgr.add_password(None, top_level_url, username, password) >>> handler = urllib2.HTTPBasicAuthHandler(password_mgr) >>> opener = urllib2.build_opener(handler) >>> a_url = "https://investor.firstrade.com/firstrade/login.do" >>> f = opener.open(a_url) >>> a = f.read() >>> print (a) but it replied login page after login. It looks like they are using cookie. Bellow line can be find in header Set-Cookie: JSESSIONID=351CE048D9FEAD01E21604129D38725C; Path=/; Secure On the web I found user guide explaining coookie login. However I do not understand how to combine now password and cookie login if this will solve the problem at first place... http://www.voidspace.org.uk/python/articles/cookielib.shtml#fetching-webpages CODE SAMPLE to be able to solve the problem very appreciated.. There is by pass solution using Web Recorder Macro. However it will be much better to BE ABLE TO handle entire process with Python.. ad 2.) Filling data to form / getting beck server values. I need server reply from the same web side we are discussing in point 1. Here is Code sample: import urllib import urllib2 url = 'https://investor.firstrade.com/firstrade/mainmenu.do' user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' values = {'symbol' : 'xsnx'} data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() a.) I do not understand where can I find currect fields names for values in the above code sample (in our case "Symbol" is written before Text box (look attached print screen. HTML code of main side is attached file Firstrade_MainSideHTML.rtf) where you can write stock ticker and than press a button. Server replied real time stock data which I would like to read)? b.) Probably code will be more complex as sample code above as code has to take care also for proper authorisation.. Sorry for taking your time. Your help would be very useful as I stacked with this. Being able to handle URL requests is very important now days... Cheers, Fedo ____________________ http://www.email.si/ ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: Firstrade_MainSide.jpg Type: image/pjpeg Size: 45800 bytes Desc: Firstrade_MainSide.jpg URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/3b4ac3cd/attachment-0001.bin> -------------- next part -------------- A non-text attachment was scrubbed... Name: Firstrade_MainSideHTML.rtf Type: application/msword Size: 41489 bytes Desc: Firstrade_MainSideHTML.rtf URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/3b4ac3cd/attachment-0001.wiz> From alan.gauld at btinternet.com Fri Aug 1 12:21:43 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Aug 2008 11:21:43 +0100 Subject: [Tutor] Mixing in and Mixing out classes in python References: <g6tdgh$sps$1@ger.gmane.org> <160626.42794.qm@web32807.mail.mud.yahoo.com> Message-ID: <g6uo01$5vi$1@ger.gmane.org> "Tomaz Bevec" <tomazbevec at yahoo.com> wrote > I'm working on a simulation of cellular growth patterns ...and cells > can potentially gain and lose these "behaviors" over the course > of the simulation. OK, That might be a valid scenario. But personally I'd probably implement that as an attribute of the cell - a list of behaviours and build a Behaviour class with subclasses. The methods of which take a Cell class as their argument. It is then trivial to add remove behaviours. And simply call them in a loop for b in self.behavious: b.doit(self) Or maybe have a dictionary of behaviours if you even want to call specific ones. eg def myMeth(self): # do sometjing try: self.behaviours['behaviourMyMeth'](self) except KeyError: pass # do the rest > I have however thought of a number of ways to work around this, > and per your suggestion I think I'll just try something else, I'd come back to the old OOP adage, inheritance is for Is-A relationships. Is you Cell a behaviour or does it Have-A behaviour? With mixins that adage tends to get bent since mixins are often functional in nature but if the function is not intrinsic to the class I tend to use delegation. > any idea on how to dynamically mix out I'd be glad to here it. I don't know but I'm sure its possible if you understand the class internals well enough. Regards, Alan G. From marc.tompkins at gmail.com Fri Aug 1 12:20:43 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 1 Aug 2008 03:20:43 -0700 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <279879.31091.qm@web50107.mail.re2.yahoo.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: <40af687b0808010320o5afcffb7t46f8b193b11feaee@mail.gmail.com> On Thu, Jul 31, 2008 at 8:16 PM, Angela Yang <angelayian at yahoo.com> wrote: > Hi, > > I have a list of values for one key. How do I specify this data structure? > > First tried, > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs. But I need key -> multiple > values. > > Do you have some example how to specify this? > > Angela > Each "value" can, itself, be a container - a tuple, a list, or another dictionary. dictTuple = {"a":(1,2,3), "b":(4,5,6)} dictList = {"a":[1,2,3], "b":[4,5,6]} dictDict = {"a":{"c":"1","d":"2","e":"3"}, "b":{"f":"4","g":"5","h":"6"}} Retrieving values: valValue = dictTuple["a"][0] # 1 valValue = dictTuple["b"][2] # 6 Lists work just the same: valValue = dictList["a"][0] # 1 valValue = dictList["b"][2] # 6 Dictionaries are, well, like dictionaries: valValue = dictDict["a"]["c"] # 1 valValue = dictDict["b"]["h"] # 6 Hope that helps.... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/c6ce3a88/attachment.htm> From alan.gauld at btinternet.com Fri Aug 1 12:25:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Aug 2008 11:25:53 +0100 Subject: [Tutor] how do I create a lists of values associated with a key? References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: <g6uo7r$6p3$1@ger.gmane.org> "Angela Yang" <angelayian at yahoo.com> wrote > But for dictionaries, it is key - value pairs. But I need key -> > multiple values. But a value can be a list. d = {} d['odd'] = [1,3,5,7] d['even'] = [2,4,6,8] print d['odd'][2] # = 5 See the Raw Materials top[ic in my tutorial for another example using a dictionary to store address data: >>> addressBook = { ... 'Fred' : ['Fred', '9 Some St',' Anytown', '0123456789'], ... 'Rose' : ['Rose', '11 Nother St', 'SomePlace', '0987654321'] ... }>>> print addressBook['Rose'] ['Rose', '11 Nother St', 'SomePlace', '0987654321'] >>> print addressBook['Fred'][3] 0123456789 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tomazbevec at yahoo.com Fri Aug 1 12:25:26 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Fri, 1 Aug 2008 03:25:26 -0700 (PDT) Subject: [Tutor] __getattribute__ instead of Mixing in and Mixing out classes in python In-Reply-To: <1c2a2c590807311729m6966b118q3b31b937eda94732@mail.gmail.com> Message-ID: <131953.81675.qm@web32807.mail.mud.yahoo.com> Thanks for your suggestion, Kent. I've looked into it a little bit and I think its probably the right way to go. --- On Thu, 7/31/08, Kent Johnson <kent37 at tds.net> wrote: > From: Kent Johnson <kent37 at tds.net> > Subject: Re: [Tutor] Mixing in and Mixing out classes in python > To: tomazbevec at yahoo.com > Cc: "Tutor Python" <tutor at python.org> > Date: Thursday, July 31, 2008, 5:29 PM > On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec > <tomazbevec at yahoo.com> wrote: > > Thanks for your reply Alan, > > > > I am partially asking out of interest, but I also have > a potential application. > > > > I'm working on a simulation of cellular growth > patterns (basically cell instances interacting > stochastically on a lattice). Anyway, there are many > different cell "behaviors" that I have to > simulate, and cells can potentially gain and lose these > "behaviors" over the course of the simulation. It > would be too much to put every behavior function in the cell > class, so I'm writing each behavior as a mixin and > mixing it in (and initializing it) when necessary or when > biological function is gained by the cells. > > Perhaps you could keep the behaviors in a dictionary? You > could > override __getattr__() in the cell class to look up > attributes whose > names start with 'behavior' in the dict. > > Kent From benoit.thiell at cern.ch Fri Aug 1 12:29:01 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Fri, 1 Aug 2008 12:29:01 +0200 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <40af687b0808010320o5afcffb7t46f8b193b11feaee@mail.gmail.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> <40af687b0808010320o5afcffb7t46f8b193b11feaee@mail.gmail.com> Message-ID: <alpine.DEB.1.10.0808011225430.3743@pcuds30> Dear Angela, in order to do this, the setdefault function of the dictionaries is very useful. For example: mydict = {} mylist = mydict.setdefault(mykey, []) mylist.append(myvalue) "setdefault" either returns the already existing list or sets a new list for the key and returns it. Regards, Benoit Thiell. On Fri, 1 Aug 2008, Marc Tompkins wrote: > > > On Thu, Jul 31, 2008 at 8:16 PM, Angela Yang <angelayian at yahoo.com> wrote: > Hi, > > I have a list of values for one key.? How do I specify this data structure? > > First tried, > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs.? But I need key -> multiple values. > > Do you have some example how to specify this? > > Angela > > > Each "value" can, itself, be a container - a tuple, a list, or another dictionary. > > dictTuple = {"a":(1,2,3), "b":(4,5,6)} > dictList = {"a":[1,2,3], "b":[4,5,6]} > dictDict = {"a":{"c":"1","d":"2","e":"3"}, "b":{"f":"4","g":"5","h":"6"}} > > Retrieving values: > valValue = dictTuple["a"][0]? # 1 > valValue = dictTuple["b"][2]? # 6 > > Lists work just the same: > valValue = dictList["a"][0]? # 1 > valValue = dictList["b"][2]? # 6 > > Dictionaries are, well, like dictionaries: > valValue = dictDict["a"]["c"]? # 1 > valValue = dictDict["b"]["h"]? # 6 > > > Hope that helps.... > > -- > www.fsrtechnologies.com > > From kent37 at tds.net Fri Aug 1 12:41:59 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Aug 2008 06:41:59 -0400 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? In-Reply-To: <20080801073939.974DC8CEF6@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> Message-ID: <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> On Fri, Aug 1, 2008 at 3:39 AM, Federo <federo at email.si> wrote: > Hi .. > > I have to admit that Python is really surprising me. It was lucky day a few > weeks ago I firts time start using Python. Lot's of things realy can be done > with short learning curve. Your user guieds was best place to start! > > Below is problem I am unable to solve. I would appreciate your advice or > even better code sample. The problem is URL authorisation. I have a writeup on form-based authentication here: http://personalpages.tds.net/~kent37/kk/00010.html#e10form-based-authentication Kent From kent37 at tds.net Fri Aug 1 12:45:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Aug 2008 06:45:53 -0400 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <279879.31091.qm@web50107.mail.re2.yahoo.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> Message-ID: <1c2a2c590808010345o560fbeccwdb5a788acd57251f@mail.gmail.com> On Thu, Jul 31, 2008 at 11:16 PM, Angela Yang <angelayian at yahoo.com> wrote: > Hi, > > I have a list of values for one key. How do I specify this data structure? > > First tried, > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs. But I need key -> multiple > values. A dict or defaultdict with list values would work well here. The defaultdict has the advantage of not requiring any user code to handle missing keys: In [7]: from collections import defaultdict In [8]: c=defaultdict(list) In [9]: c['abby'].append('apprentice1') In [10]: c['abby'].append('apprentice2') In [11]: c Out[11]: defaultdict(<type 'list'>, {'abby': ['apprentice1', 'apprentice2']}) Kent From monjissvel at googlemail.com Fri Aug 1 12:49:00 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 10:49:00 +0000 Subject: [Tutor] how do I create a lists of values associated with a key? In-Reply-To: <e2f191310808010343l5f7cfc0eu9cbcb1430346504c@mail.gmail.com> References: <279879.31091.qm@web50107.mail.re2.yahoo.com> <e2f191310808010343l5f7cfc0eu9cbcb1430346504c@mail.gmail.com> Message-ID: <e2f191310808010349l326f95b7od58b4541cec85c40@mail.gmail.com> 2008/8/1 Angela Yang <angelayian at yahoo.com> > > > collection = [] > collection['abby'].append('apprentice1') > collection['abby'].append('apprentice2') > > That did not work because list index is not numeric. > But for dictionaries, it is key - value pairs. But I need key -> multiple values. > > Do you have some example how to specify this? > You already know this : Collection1 = [] Collection2 = [] Collection1.append('apprentice1') Collection1.append('apprentice2') if you add a MainCollection to the picture which can be coded like this: MainCollection = {'Collection1':[], 'Collection2':[]} Adding elements to a Collection is as simple as this interactive session demonstrates : Python 2.4.4 (#2, Apr 15 2008, 23:43:20) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> >>> MainCollection = {'Collection1':[], 'Collection2':[]} >>> type(MainCollection) <type 'dict'> >>> MainCollection['Collection1'] [] >>> MainCollection['Collection1'].append('aa') >>> MainCollection['Collection1'] ['aa'] >>> MainCollection['Collection1'].append('bb') >>> MainCollection['Collection1'] ['aa', 'bb'] From monjissvel at googlemail.com Fri Aug 1 13:04:48 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:04:48 +0000 Subject: [Tutor] Unzipping a list In-Reply-To: <20080708132032.295daef7@rental-faheem.bangalore.atlantiscomputing.com> References: <20080708102233.7715f1db@rental-faheem.bangalore.atlantiscomputing.com> <20080708132032.295daef7@rental-faheem.bangalore.atlantiscomputing.com> Message-ID: <e2f191310808010404o113115au9208d9eece227f1c@mail.gmail.com> > > >>> answers= ['ask','tell','repeat','sell'] > >>> > >>> > >>> a = '/usr/program/bin -o '+ ' '.join(answers) > >>> print a > /usr/program/bin -o ask tell repeat sell > 2008/7/8 Faheem <faheem at atlantiscomputing.com>: > Hey all, > > If anyone is interested I found this while googling > > answers= ['ask'.'tell','repeat','sell'] > > def unzip(answers): > unzipped = "".join(answers) # if all items are strings > unzipped = ", ".join(map(str, answers)) > unzipped = " ".join(str(v) for v in answers if v > 0) > return unzipped > > will give the following > > ask tell repeat sell > > :) > >> hey all, >> How can i pass the elements of a list in the follwoing manner? >> >> L =['ask'.'tell','repeat','sell'] >> >> To illustrate my question: >> how can i pass the above list as follows >> >> "/some/program/run -o ask tell repeat sell" >> >> thanks in advance > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/34a32512/attachment.htm> From monjissvel at googlemail.com Fri Aug 1 13:13:09 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:13:09 +0000 Subject: [Tutor] Newbie In-Reply-To: <562071.37071.qm@web59516.mail.ac4.yahoo.com> References: <562071.37071.qm@web59516.mail.ac4.yahoo.com> Message-ID: <e2f191310808010413y4ad85bf4y2f54df47d56741c0@mail.gmail.com> if you remove the comma after the print i for i in range(10) : print i print "Goodbye World!" your problem will be solved, the comma in a print statement means ' ' or space. THREADING is a word that means something else than having two strings on the same line. 2008/7/23 Sam Last Name <the_sam_smart at yahoo.com> > Hey guys, I'm wanting to learn Python and eventually how to program with > it. I'm 16 and very eager to learn. I already have a question. > > Heres my script: > print "Hello World!" > print "Here are the ten numbers from 0 to 9" > for i in range(10) : > print i, > print "Goodbye World!" > > Result of my script : > Hello World! > Here are the ten numbers from 0 to 9 > 0 Goodbye World! > 1 Goodbye World! > 2 Goodbye World! > 3 Goodbye World! > 4 Goodbye World! > 5 Goodbye World! > 6 Goodbye World! > 7 Goodbye World! > 8 Goodbye World! > 9 Goodbye World! > > > I don't Understand. I have an idea it something like Goodbye world is > threading together with the numbers? Feedback is Thanked :) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/7f9aae70/attachment.htm> From monjissvel at googlemail.com Fri Aug 1 13:15:54 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:15:54 +0000 Subject: [Tutor] Tutor Newbie In-Reply-To: <138002.84298.qm@web59507.mail.ac4.yahoo.com> References: <138002.84298.qm@web59507.mail.ac4.yahoo.com> Message-ID: <e2f191310808010415o23a961d2mef06ff34f5fa12fb@mail.gmail.com> it would take learning to use some of the modules that help create GUIs. they are : wx and Tkinter 2008/7/25 Sam Last Name <the_sam_smart at yahoo.com> > Hey guys, need some info on "programs" :) > > > Heres a Very simple Script that works with basically any numbers. > > > width = input("What is the Width?") > length = input("What is the Length?") > area = width*length > print area > # my question is what would it take (programs, extra stuff in script, > ect..) to make this a nice looking usable desktop program? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/2915d554/attachment.htm> From monjissvel at googlemail.com Fri Aug 1 13:37:16 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Fri, 1 Aug 2008 11:37:16 +0000 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? In-Reply-To: <20080801073939.974DC8CEF6@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> Message-ID: <e2f191310808010437l23dd6ed4va7ef50c81e2cf680@mail.gmail.com> Here is some code, it will help you manage cookies, & stay logged in to the website for further queries. import os, sys, time, urllib, urllib2, cookielib, re > > cj=cookielib.LWPCookieJar() > headers={'User-Agent' : user_agent} > opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > get_login=urllib2.urlopen('https://www.website.com/login_page.html') > > recieved_login_page = get_login.readlines() > > for line in recieved_login_page: > #you've got to parse each line in the page > #and extract information from it & assign it to variables > > #those variables you just extracted you've got to put them in this > dictionary > values={'username':'xxxxxxxxx', 'pass':'xxxxxxxxx', 'submit' : 'submit', > 'anothervar':'xxxx'} > data=urllib.urlencode(values) > > req=urllib2.Request('https://www.website.com/form_action.php', data, > headers) #I think "https://investor.firstrade.com/firstrade/login.do" > response=urllib2.urlopen(req) > ofcourse this is just example code and you should replace some variables with your own, but it should work for your case if you know where the form submits its data & what data it submits (you put this data in the values dict & then encode it & use it to authenticate and the opener (urllib2.install_opener(opener)) should keep you logged in to the page because it keeps track of cookies for you. 2008/8/1 Federo <federo at email.si> > Hi .. > > I have to admit that Python is really surprising me. It was lucky day a few > weeks ago I firts time start using Python. Lot's of things realy can be > done > with short learning curve. Your user guieds was best place to start! > > Below is problem I am unable to solve. I would appreciate your advice or > even better code sample. The problem is URL authorisation. I try to > approaches > but no luck so far. Two problems: > > 1.) Being able to logon using Python code > 2.) Being able to send data to a form and get back server reply > > ad 1.) > The Two pages I try to open: > > Login: > https://investor.firstrade.com/firstrade/login.do > Main page after login: > https://investor.firstrade.com/firstrade/mainmenu.do > > I have tried bellow code (with currect user name and password of course): > >>> import urllib2 > >>> password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() > >>> protocol = 'https://' > >>> username = 'user' > >>> password = 'pass' > >>> top_level_url = "investor.firstrade.com/firstrade/login.do" > >>> password_mgr.add_password(None, top_level_url, username, password) > >>> handler = urllib2.HTTPBasicAuthHandler(password_mgr) > >>> opener = urllib2.build_opener(handler) > >>> a_url = "https://investor.firstrade.com/firstrade/login.do" > >>> f = opener.open(a_url) > >>> a = f.read() > >>> print (a) > > but it replied login page after login. It looks like they are using cookie. > Bellow line can be find in header > Set-Cookie: JSESSIONID=351CE048D9FEAD01E21604129D38725C; Path=/; Secure > > On the web I found user guide explaining coookie login. However I do not > understand how to combine now password and cookie login if this will solve > the > problem at first place... > > http://www.voidspace.org.uk/python/articles/cookielib.shtml#fetching-webpages > > CODE SAMPLE to be able to solve the problem very appreciated.. > > There is by pass solution using Web Recorder Macro. However it will be much > better to BE ABLE TO handle entire process with Python.. > > ad 2.) Filling data to form / getting beck server values. I need server > reply > from the same web side we are discussing in point 1. > > Here is Code sample: > import urllib > import urllib2 > > url = 'https://investor.firstrade.com/firstrade/mainmenu.do' > user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > values = {'symbol' : 'xsnx'} > > data = urllib.urlencode(values) > req = urllib2.Request(url, data) > response = urllib2.urlopen(req) > the_page = response.read() > > a.) I do not understand where can I find currect fields names for values > in the above code sample (in our case "Symbol" is written before Text box > (look > attached print screen. HTML code of main side is attached file > Firstrade_MainSideHTML.rtf) > where you can write stock ticker and than press a button. Server replied > real > time stock data which I would like to read)? > b.) Probably code will be more complex as sample code above as code has to > take > care also for proper authorisation.. > > Sorry for taking your time. Your help would be very useful as I stacked > with > this. Being able to handle URL requests is very important now days... > > Cheers, Fedo > > ____________________ > http://www.email.si/ > > ____________________ > http://www.email.si/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/6a2d4ef2/attachment-0001.htm> From agent.krycek at gmail.com Fri Aug 1 20:47:52 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Fri, 1 Aug 2008 12:47:52 -0600 Subject: [Tutor] Logging In To Forum Message-ID: <a4f6ec110808011147s5f55b99bv796c8621dbdd261a@mail.gmail.com> Hello, I would like to have my script log in to a vBulletin forum. My script does seem to do this (as I can check my control panel, etc.). But although I can get access to my account, the forum fails to update the date when I last visited. That date updates just fine when I do it manually through a browser. I was wondering if I was maybe messing something up with cookies. Any suggestions would be appreciated. Thanks! #!/usr/bin/python # forumlogin.py # Logs into vBulletin forum import urllib2, time import cgitb; cgitb.enable() def main(): print "Content-type: text/html\n" url = "http://forums.x10hosting.com/login.php?do=login" queryString = "..." opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) response = opener.open(url, queryString) logfile() response.close() def logfile(): fileIn = open("../logfile.txt", "a") fileIn.write("\n") fileIn.write(time.ctime()) fileIn.close() *if* __name__ == "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/d074b35f/attachment.htm> From kent37 at tds.net Fri Aug 1 21:20:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Aug 2008 15:20:41 -0400 Subject: [Tutor] Logging In To Forum In-Reply-To: <a4f6ec110808011147s5f55b99bv796c8621dbdd261a@mail.gmail.com> References: <a4f6ec110808011147s5f55b99bv796c8621dbdd261a@mail.gmail.com> Message-ID: <1c2a2c590808011220x10d8564er8d37ea3a538f816f@mail.gmail.com> On Fri, Aug 1, 2008 at 2:47 PM, Alex Krycek <agent.krycek at gmail.com> wrote: > Hello, > > I would like to have my script log in to a vBulletin forum. My script does > seem to do this (as I can check my control panel, etc.). But although I can > get access to my account, the forum fails to update the date when I last > visited. That date updates just fine when I do it manually through a > browser. I was wondering if I was maybe messing something up with cookies. > Any suggestions would be appreciated. Thanks! You might try actually reading the response data with response.read(). Otherwise you should look closely at the interaction with the browser; you need to mimic that. Firebug and other browser tools can help. Kent From agent.krycek at gmail.com Fri Aug 1 21:25:46 2008 From: agent.krycek at gmail.com (Alex Krycek) Date: Fri, 1 Aug 2008 13:25:46 -0600 Subject: [Tutor] Logging In To Forum In-Reply-To: <1c2a2c590808011220x10d8564er8d37ea3a538f816f@mail.gmail.com> References: <a4f6ec110808011147s5f55b99bv796c8621dbdd261a@mail.gmail.com> <1c2a2c590808011220x10d8564er8d37ea3a538f816f@mail.gmail.com> Message-ID: <a4f6ec110808011225r51a125a3hfc4a872066dd9966@mail.gmail.com> Kent, I tried reading several pages with the read() function. Unfortunately nothing changed. I'll take a look at Firebug. Thanks. On Fri, Aug 1, 2008 at 1:20 PM, Kent Johnson <kent37 at tds.net> wrote: > On Fri, Aug 1, 2008 at 2:47 PM, Alex Krycek <agent.krycek at gmail.com> > wrote: > > Hello, > > > > I would like to have my script log in to a vBulletin forum. My script > does > > seem to do this (as I can check my control panel, etc.). But although I > can > > get access to my account, the forum fails to update the date when I last > > visited. That date updates just fine when I do it manually through a > > browser. I was wondering if I was maybe messing something up with > cookies. > > Any suggestions would be appreciated. Thanks! > > You might try actually reading the response data with response.read(). > Otherwise you should look closely at the interaction with the browser; > you need to mimic that. Firebug and other browser tools can help. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080801/6977f1b7/attachment.htm> From fredp101 at mac.com Sat Aug 2 07:41:06 2008 From: fredp101 at mac.com (Fred @ Mac) Date: Fri, 01 Aug 2008 22:41:06 -0700 Subject: [Tutor] Scan Directory for files Message-ID: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Hello, new to python, so please go easy on me! I am using for f in os.listdir(watch_dir): tree = ET.parse(f) for shot in tree.findall('Shot'): ..do stuff.. to scan a directory for specific files (xml files specifically). But my script fails if, for example, a directory also exists in "watch_dir" How can i restructure this so it only returns a list of the .xml files in that directory, ignores other files and or directories in "watch_dir" Thanks! From jeff at drinktomi.com Sat Aug 2 08:26:22 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Fri, 1 Aug 2008 23:26:22 -0700 Subject: [Tutor] Is anybody out there who could help me with URL Authentication? In-Reply-To: <20080801073939.974DC8CEF6@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> Message-ID: <4F80CB79-A34E-41BA-8A52-2B7D2B3CF86E@drinktomi.com> On Aug 1, 2008, at 12:39 AM, Federo wrote: > > Below is problem I am unable to solve. I would appreciate your > advice or > even better code sample. The problem is URL authorisation. I try to > approaches > but no luck so far. Two problems: > > 1.) Being able to logon using Python code > 2.) Being able to send data to a form and get back server reply While it's possible to cobble together something using urllib and htmlparser, you're much better off using mechanize. It's basically an entire browser in a library. It handles http authentication, cookies, form processing, etc. For more details check out the project's page at: http://wwwsearch.sourceforge.net/mechanize/ - Jeff Younker - jeff at drinktomi.com - From steve.poe at gmail.com Sat Aug 2 09:00:23 2008 From: steve.poe at gmail.com (Steve Poe) Date: Sat, 2 Aug 2008 00:00:23 -0700 Subject: [Tutor] Scan Directory for files In-Reply-To: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> References: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Message-ID: <87E0D850-D657-4D3C-A5C1-27904B0BCB37@gmail.com> Fred, What is/are the exact error message(s)? You may want to look at the module glob. Steve Ar e you typing this in the python interpreter or On Aug 1, 2008, at 10:41 PM, Fred @ Mac wrote: > Hello, > > new to python, so please go easy on me! > > I am using > > for f in os.listdir(watch_dir): > tree = ET.parse(f) > for shot in tree.findall('Shot'): > ..do stuff.. > > to scan a directory for specific files (xml files specifically). > > But my script fails if, for example, a directory also exists in > "watch_dir" > > How can i restructure this so it only returns a list of the .xml > files in that directory, ignores other files and or directories in > "watch_dir" > > Thanks! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Aug 2 10:07:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 09:07:11 +0100 Subject: [Tutor] Scan Directory for files References: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Message-ID: <g714fq$r9j$1@ger.gmane.org> "Fred @ Mac" <fredp101 at mac.com> wrote > for f in os.listdir(watch_dir): > tree = ET.parse(f) > for shot in tree.findall('Shot'): > ..do stuff.. > > But my script fails if, for example, a directory also exists in > "watch_dir" Take a look at os.walk which allows recursive traversal of a directory structure. There is a short discussion in the OS topic on my web tutor. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sat Aug 2 12:07:43 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 03:07:43 -0700 Subject: [Tutor] I can't believe this needs to be this complex Message-ID: <20080802100759.4A97D1E4003@bag.python.org> I'm pretty new to Python's dictionaries, but I had a need for a function that would find the values in a dict that have more than one key each. It took me several hours to write. See <http://py77.python.pastebin.com/f397582d8>. Seems to do the job, both with the example shown, and with the dict of colors at <http://py77.python.pastebin.com/f796752ff>. But I can't believe the function needs to be so complex. And also, I suppose I've reinvented the wheel (again). Please instruct me. My apologies in advance to Kent for not using a single list comprehension. Thanks, Dick Moores From andreengels at gmail.com Sat Aug 2 12:27:34 2008 From: andreengels at gmail.com (Andre Engels) Date: Sat, 2 Aug 2008 11:27:34 +0100 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <20080802100759.4A97D1E4003@bag.python.org> References: <20080802100759.4A97D1E4003@bag.python.org> Message-ID: <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.com> On Sat, Aug 2, 2008 at 11:07 AM, Dick Moores <rdm at rcblue.com> wrote: > I'm pretty new to Python's dictionaries, but I had a need for a function > that would find the values in a dict that have more than one key each. It > took me several hours to write. See > <http://py77.python.pastebin.com/f397582d8>. Seems to do the job, both with > the example shown, and with the dict of colors at > <http://py77.python.pastebin.com/f796752ff>. > > But I can't believe the function needs to be so complex. And also, I suppose > I've reinvented the wheel (again). Please instruct me. > > My apologies in advance to Kent for not using a single list comprehension. Well, list comprehension does indeed seem the solution to your problem, although a single list comprehension would not be necessary. I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is untested, I have no Python on the computer I am working on now), or http://py77.python.pastebin.com/f76ba5002 to indeed just use a single list comprehension (or rather, two nested list comprehensions, again untested for the above reason). -- Andr? Engels, andreengels at gmail.com From rdm at rcblue.com Sat Aug 2 12:49:08 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 03:49:08 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.com> Message-ID: <20080802104920.B10F21E4003@bag.python.org> At 03:27 AM 8/2/2008, Andre Engels wrote: >Content-Transfer-Encoding: >base64Content-Disposition: inlineOn Sat, Aug 2, >2008 at 11:07 AM, Dick Moores <rdm at rcblue.com> wrote: > > I'm pretty new to Python's dictionaries, but I had a need for a function > > that would find the values in a dict that have more than one key each. It > > took me several hours to write. See > > > <http://py77.python.pastebin.com/f397582d8??Y[\???H??????]??Hexample > shown, and with the dict of colors at> > <http://py77.python.pastebin.com/f796752ff>. > > >?]H?[???[Y at ve the function needs to be so complex. And also, I suppose > > I've reinvented the wheel (again). Please instruct me. > > >^H\???Y\?[?Y?[??H??[??????\?[??H?@ngle list comprehension. > >Well, list comprehension does indeed seem the solution to your >problem, although a single list comprehension would not be necessary. >I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is >untested, I have no Python on the computer I am working on now), or >http://py77.python.pastebin.com/f76ba5002 to indeed just use a single >list comprehension (or rather, two nested list comprehensions, again >untested for the above reason). You genius! How could you answer so quickly and accurately (20 minutes!) without access to Python? Both of your scripts work, after I corrected one typo. See <http://py77.python.pastebin.com/f7b6e51e8>. Thanks! Dick Moores From rdm at rcblue.com Sat Aug 2 13:18:09 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 04:18:09 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <20080802104920.B10F21E4003@bag.python.org> References: <20080802100759.4A97D1E4003@bag.python.org> <6faf39c90808020327q3bec47e4ra046d2dd41af22c1@mail.gmail.com> <20080802104920.B10F21E4003@bag.python.org> Message-ID: <20080802111945.A6E0C1E4003@bag.python.org> At 03:49 AM 8/2/2008, Dick Moores wrote: >At 03:27 AM 8/2/2008, Andre Engels wrote: >>Content-Transfer-Encoding: >>base64Content-Disposition: inlineOn Sat, Aug 2, >>2008 at 11:07 AM, Dick Moores <rdm at rcblue.com> wrote: >> > I'm pretty new to Python's dictionaries, but I had a need for a function >> > that would find the values in a dict that have more than one key each. It >> > took me several hours to write. See >> > >> <http://py77.python.pastebin.com/f397582d8??Y[\???H??????]??Hexample >> shown, and with the dict of colors at> >> <http://py77.python.pastebin.com/f796752ff>. >> > >>?]H?[???[Y at ve the function needs to be so complex. And also, I suppose >> > I've reinvented the wheel (again). Please instruct me. >> > >>^H\???Y\?[?Y?[??H??[??????\?[??H?@ngle list comprehension. >> >>Well, list comprehension does indeed seem the solution to your >>problem, although a single list comprehension would not be necessary. >>I came to http://py77.python.pastebin.com/m4dcbb34f (note: this is >>untested, I have no Python on the computer I am working on now), or >>http://py77.python.pastebin.com/f76ba5002 to indeed just use a single >>list comprehension (or rather, two nested list comprehensions, again >>untested for the above reason). > >You genius! How could you answer so quickly and >accurately (20 minutes!) without access to Python? > >Both of your scripts work, after I corrected one >typo. See <http://py77.python.pastebin.com/f7b6e51e8>. And here's your one-liner (<http://py77.python.pastebin.com/f789096e9>) at work on the dict of colors at <http://py77.python.pastebin.com/f796752ff>. Dick From kent37 at tds.net Sat Aug 2 13:49:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 07:49:51 -0400 Subject: [Tutor] Scan Directory for files In-Reply-To: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> References: <738289AE-5D56-4301-A4AE-A49947E77EF8@mac.com> Message-ID: <1c2a2c590808020449h5499f2ebw4aabb691e9c30675@mail.gmail.com> On Sat, Aug 2, 2008 at 1:41 AM, Fred @ Mac <fredp101 at mac.com> wrote: > Hello, > > new to python, so please go easy on me! > > I am using > > for f in os.listdir(watch_dir): > tree = ET.parse(f) Should be ET.parse(os.path.join(watch_dir, f)) I think... > for shot in tree.findall('Shot'): > ..do stuff.. > > to scan a directory for specific files (xml files specifically). > > But my script fails if, for example, a directory also exists in "watch_dir" > > How can i restructure this so it only returns a list of the .xml files in > that directory, ignores other files and or directories in "watch_dir" The glob module can filter file names based on patterns. os.path.isfile() will tell you if something is a file. So for example: pattern = os.path.join(watch_dir, "*.xml") for f in glob.glob(pattern): if not os.path.isfile(f): #already did the join in the pattern continue tree = ET.parse(f) Jason Orendorff's path module is useful for this also though the doc site seems to be down: http://pypi.python.org/pypi/path.py/2.2 Kent From kent37 at tds.net Sat Aug 2 14:02:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 08:02:17 -0400 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <20080802100759.4A97D1E4003@bag.python.org> References: <20080802100759.4A97D1E4003@bag.python.org> Message-ID: <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores <rdm at rcblue.com> wrote: > I'm pretty new to Python's dictionaries, but I had a need for a function > that would find the values in a dict that have more than one key each. >From your sample output it appears that you want not just the values, but a list of (value, keys) pairs for which there are more than one key. It is easy to just build a reverse dict and filter its items: In [15]: from collections import defaultdict In [16]: rev=defaultdict(list) In [18]: for k, v in d.iteritems(): rev[v].append(k) In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ] Out[20]: [[1, ['a', 'e', 'g']], [2, ['b', 'f', 'i', 'h']], [4, ['d', 'j']], ['U.S. Senator', ['John McCain', 'Barack Obama']], [56, [45, 55]]] This also has the advantage of making only two passes over the data so its performance should be O(n). Your solution and Andre's make one or more passes over the data for each data element so they will have O(n*n) performance meaning for a large dict they could be very slow. Kent From rdm at rcblue.com Sat Aug 2 15:27:21 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 06:27:21 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> Message-ID: <20080802132734.A50001E4016@bag.python.org> At 05:02 AM 8/2/2008, Kent Johnson wrote: >On Sat, Aug 2, 2008 at 6:07 AM, Dick Moores <rdm at rcblue.com> wrote: > > I'm pretty new to Python's dictionaries, but I had a need for a function > > that would find the values in a dict that have more than one key each. > > From your sample output it appears that you want not just the values, >but a list of (value, keys) pairs for which there are more than one >key. It is easy to just build a reverse dict and filter its items: > >In [15]: from collections import defaultdict >In [16]: rev=defaultdict(list) >In [18]: for k, v in d.iteritems(): > rev[v].append(k) > >In [20]: [ [v, keys] for v, keys in rev.iteritems() if len(keys) > 1 ] > >Out[20]: >[[1, ['a', 'e', 'g']], > [2, ['b', 'f', 'i', 'h']], > [4, ['d', 'j']], > ['U.S. Senator', ['John McCain', 'Barack Obama']], > [56, [45, 55]]] > >This also has the advantage of making only two passes over the data so >its performance should be O(n). Your solution and Andre's make one or >more passes over the data for each data element so they will have >O(n*n) performance meaning for a large dict they could be very slow. Wow, the genius' genius appears! You're using some Python tools I didn't know about. More study! I made a function of your code and time tested it against mine, using as d that dict of colors at <http://py77.python.pastebin.com/f796752ff>. Yours is 73 times faster! In [12]: run -t -N10 fcn_values_dupe_keys.py Time was 0.297 seconds Time was 0.328 seconds Time was 0.344 seconds Time was 0.328 seconds Time was 0.313 seconds Time was 0.344 seconds Time was 0.39 seconds Time was 0.297 seconds Time was 0.312 seconds Time was 0.297 seconds IPython CPU timings (estimated): Total runs performed: 10 Times : Total Per run User : 3.3092253345 s, 0.33092253345 s. System: 0.0 s, 0.0 s. In [13]: run -t -N10 kent1.py Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0.015 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds Time was 0 seconds IPython CPU timings (estimated): Total runs performed: 10 Times : Total Per run User : 0.044969961266 s, 0.0044969961266 s. System: 0.0 s, 0.0 s. BTW Kent, I'm going to take this opportunity to ask you about "System" in the IPython timing results. It's always zero for the code I time. What's an example of code that would have System be greater than zero? And what's the distinction between User and System? (I'm using Win XP, if that's relevant.) Thanks, Dick From jtp at nc.rr.com Sat Aug 2 16:34:48 2008 From: jtp at nc.rr.com (James) Date: Sat, 2 Aug 2008 10:34:48 -0400 Subject: [Tutor] Classes in separate files Message-ID: <e107b4ff0808020734v665b3395pb5d5e42de62c7c37@mail.gmail.com> All, I've started tinkering (just a little) with classes, primarily because I have to. (I've never been a huge fan of OOP, but can tolerate it when used properly). I'll be the first to admit that I don't know much about how to program "correctly" when dealing with objects, however, so any thoughts in the matter would be greatly appreciated. I have a few files that I use as "libraries" which contain dozens of functions that I use across a wide array of programs. This works fine when I want to invoke a function, pass in a few parameters, and then get something back. I'm now trying to put a few classes which I know I will be using repeatedly in a separate file, as well. The issue is, however, that I'm not sure the "best" way to pass things into classes, and the "best" way to get something back. I have a main file, main.py. It's going to create several instances that are defined by a class in class1.py. *However*, I also need to instantiate numerous other classes defined in class2.py. class1.py has a few classes, such as - ticket (represents a ticket opened to fix bugs in a program) - ticketAnalyzer (an object who looks at all the tickets opened/available) class2.py has a few classes, as well, such as: - codemonkey (defines a person that is going to take tickets and fix them) - codereviewer (defines a person who will double check a codemonkey's work) main.py has the "main" function, and will what is actually invoked at the command line. In main.py I can instantiate an object of type ticket, an object of type ticketAnalyzer, and then instantiate code{monkey,reviewer} classes. However, how do I get codemonkey and codereviewer to call methods on the ticket and ticketAnalyzer classes? The only solution I can think of here is having the main function (in main.py) which instantiates all these objects actually *pass in* to the codemonkey and reviewer the reference to the specific objects ticketAnalyzer and ticket. Is this the best way to do it? Should I handle that behavior in the __init__ of code{monkey,reviewer}? Should I instead create a method inside of the codemonkey and reviewer classes that accepts the object pointer to the ticket objects and then interact between ticket/code* objects as such? I image it would be much easier to have everything in one file, but that goes against my grain. ;) Thoughts appreciated! -j From desm at hotmail.co.uk Sat Aug 2 16:40:14 2008 From: desm at hotmail.co.uk (desmond mansfield) Date: Sat, 2 Aug 2008 14:40:14 +0000 Subject: [Tutor] Why use lambda? In-Reply-To: <mailman.53.1217671217.6603.tutor@python.org> References: <mailman.53.1217671217.6603.tutor@python.org> Message-ID: <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> I've read some small tutorials on lambda, and how I can use it to define functions "on-the-fly". But what I don't understand, and cannot seem to find an answer to, is why I'd actually want to use it ? What can lambda do that normal function definitions cannot? Is it quicker to execute/less memory intensive? Or is it just quicker to type and easier to think about? Any answers would be appreciated. thanks, _________________________________________________________________ Make a mini you on Windows Live Messenger! http://clk.atdmt.com/UKM/go/107571437/direct/01/ From jtp at nc.rr.com Sat Aug 2 16:51:03 2008 From: jtp at nc.rr.com (James) Date: Sat, 2 Aug 2008 10:51:03 -0400 Subject: [Tutor] Classes in separate files In-Reply-To: <e107b4ff0808020734v665b3395pb5d5e42de62c7c37@mail.gmail.com> References: <e107b4ff0808020734v665b3395pb5d5e42de62c7c37@mail.gmail.com> Message-ID: <e107b4ff0808020751j98a95ddr5af13a60add84db9@mail.gmail.com> Another question on classes in separate files... main.py instantiates a class called 'testClass' inside of a file temp.py. In main.py: t = temp.testClass() So now I can access some of the variables inside of 't'. For example, let's say that in main.py, I do the following: # get a variable from the t class (I know, this is not the cleanest way to do this ;)) tempVariable = t.tempVar So here's a question...how does the object *t* (defined in the temp.py file) access a global (or even local) variable in main.py? Is it possible? What if I want the object t to write to a global variable inside of main.py...is that possible? Thanks! -j On Sat, Aug 2, 2008 at 10:34 AM, James <jtp at nc.rr.com> wrote: > All, > > I've started tinkering (just a little) with classes, primarily because > I have to. (I've never been a huge fan of OOP, but can tolerate it > when used properly). > > I'll be the first to admit that I don't know much about how to program > "correctly" when dealing with objects, however, so any thoughts in the > matter would be greatly appreciated. > > I have a few files that I use as "libraries" which contain dozens of > functions that I use across a wide array of programs. This works fine > when I want to invoke a function, pass in a few parameters, and then > get something back. I'm now trying to put a few classes which I know I > will be using repeatedly in a separate file, as well. > > The issue is, however, that I'm not sure the "best" way to pass things > into classes, and the "best" way to get something back. > > I have a main file, main.py. It's going to create several instances > that are defined by a class in class1.py. *However*, I also need to > instantiate numerous other classes defined in class2.py. > > class1.py has a few classes, such as > - ticket (represents a ticket opened to fix bugs in a program) > - ticketAnalyzer (an object who looks at all the tickets opened/available) > > class2.py has a few classes, as well, such as: > - codemonkey (defines a person that is going to take tickets and fix them) > - codereviewer (defines a person who will double check a codemonkey's work) > > main.py has the "main" function, and will what is actually invoked at > the command line. In main.py I can instantiate an object of type > ticket, an object of type ticketAnalyzer, and then instantiate > code{monkey,reviewer} classes. However, how do I get codemonkey and > codereviewer to call methods on the ticket and ticketAnalyzer classes? > > The only solution I can think of here is having the main function (in > main.py) which instantiates all these objects actually *pass in* to > the codemonkey and reviewer the reference to the specific objects > ticketAnalyzer and ticket. Is this the best way to do it? Should I > handle that behavior in the __init__ of code{monkey,reviewer}? Should > I instead create a method inside of the codemonkey and reviewer > classes that accepts the object pointer to the ticket objects and then > interact between ticket/code* objects as such? > > I image it would be much easier to have everything in one file, but > that goes against my grain. ;) > > Thoughts appreciated! > -j > From technorapture at gmail.com Sat Aug 2 17:42:10 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Sat, 2 Aug 2008 11:42:10 -0400 Subject: [Tutor] Why use lambda? In-Reply-To: <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> References: <mailman.53.1217671217.6603.tutor@python.org> <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> Message-ID: <376fbdcf0808020842q2c1efa0cw57443bfd45ab8d52@mail.gmail.com> >From what I've seen, Lambda is most useful if you're passing functions as arguments to other functions. You could use lambda to create a function on-the-fly, as you've said, and that will save you the trouble of having to write it separately. Try looking for examples on functional programming in Python to find more examples. On Sat, Aug 2, 2008 at 10:40 AM, desmond mansfield <desm at hotmail.co.uk> wrote: > > I've read some small tutorials on lambda, and how I can use it to define functions "on-the-fly". > But what I don't understand, and cannot seem to find an answer to, is why I'd actually want to use it ? > > What can lambda do that normal function definitions cannot? > Is it quicker to execute/less memory intensive? > Or is it just quicker to type and easier to think about? > > Any answers would be appreciated. thanks, > _________________________________________________________________ > Make a mini you on Windows Live Messenger! > http://clk.atdmt.com/UKM/go/107571437/direct/01/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- The ByteBaker : http://www.bytebaker.com From dineshbvadhia at hotmail.com Sat Aug 2 17:51:55 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 2 Aug 2008 08:51:55 -0700 Subject: [Tutor] removing whole numbers from text Message-ID: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> I want to remove whole numbers from text but retain numbers attached to words. All whole numbers to be removed have a leading and trailing space. For example, in "the cow jumped-20 feet high30er than the lazy 20 timing fox who couldn't keep up the 865 meter race." remove the whole numbers 20 and 865 but keep the 20 in jumped-20 and the 30 in high30er. What is the best to do this using re? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080802/8ee5256c/attachment.htm> From dyoo at cs.wpi.edu Sat Aug 2 18:26:00 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Sat, 2 Aug 2008 12:26:00 -0400 Subject: [Tutor] Why use lambda? In-Reply-To: <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> References: <mailman.53.1217671217.6603.tutor@python.org> <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> Message-ID: <d06401780808020926p1c87ef2ft2e5a6e29b20f5462@mail.gmail.com> > What can lambda do that normal function definitions cannot? > Is it quicker to execute/less memory intensive? > Or is it just quicker to type and easier to think about? Notational convenience. Think about how, in arithmetic expressions, how we're not forced to give explicit names to all the subexpressions: ######################### def hypotenuse(a, b): return ((a * a) + (b * b))**0.5 ######################### Imagine a world where we have to give explicit names to all of the subexpressions: ################### def hypotenuse(a, b): tmp1 = a * a tmp2 = b * b tmp3 = tmp1 + tmp2 tmp4 = tmp3**0.5 return tmp4 #################### Does this look funny to you? Why? Sometimes we don't care what something is named: we just want to use the value. lambda's use is motivated by the same idea: sometimes, we want to use a function value without having to give a name. Here's a toy example. #################################### def deepmap(f, datum): """Deeply applies f across the datum.""" if type(datum) == list: return [deepmap(f, x) for x in datum] else: return f(datum) #################################### If we wanted to apply a squaring on all the numbers in the nested list (while still maintaining the nested structure): [42, 43, [44, [45]]] then we can use deepmap by feeding in a square function to it. ############################## def square(x): return x * x deepmap(square, [42, 43, [44, [45]]]) ############################### An alternative way to express the above is: deepmap(lambda x: x *x, [42, 43, [44, [45]]]) Here, we avoid having to first give a name to the function value we're passing to deepmap. From alan.gauld at btinternet.com Sat Aug 2 18:50:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 17:50:12 +0100 Subject: [Tutor] Classes in separate files References: <e107b4ff0808020734v665b3395pb5d5e42de62c7c37@mail.gmail.com> Message-ID: <g7234g$853$1@ger.gmane.org> "James" <jtp at nc.rr.com> wrote > The issue is, however, that I'm not sure the "best" way to pass > things > into classes, and the "best" way to get something back. In an OOP syustem you don;t normally have to pass a lot into a method since most of the data should be internal to the object Often a single object parameter is all thats required - if any. > I have a main file, main.py. It's going to create several instances > that are defined by a class in class1.py. *However*, I also need to > instantiate numerous other classes defined in class2.py. The files issue is largely irrelevant and no different for OOP than for procedural coding. Keep related classes in a single module. Put unrelated classes in another module to ease reuse. > class1.py has a few classes, such as > - ticket (represents a ticket opened to fix bugs in a program) > - ticketAnalyzer (an object who looks at all the tickets > opened/available) Its convention to make class names start with an upperc ase letter. Attributes/methods/instances start with lowercase. As to TicketAnalyzer - why doesn't the ticket analyze itself? > class2.py has a few classes, as well, such as: > - codemonkey (defines a person that is going to take tickets and fix > them) So has a method called fix(aTicket)? > - codereviewer (defines a person who will double check a > codemonkey's work) So has a method called check(aTicket)? These two classes sound like subclasses of a common superclass - called Person maybe? > main.py has the "main" function, and will be what is actually > invoked at > the command line. In main.py I can instantiate an object of type > ticket, an object of type ticketAnalyzer, and then instantiate > code{monkey,reviewer} classes. However, how do I get codemonkey and > codereviewer to call methods on the ticket and ticketAnalyzer > classes? in the CodeMonkey.fix(aTicket) method the code can reference aTicket. as in: def fix(self, aTicket): faultType = aTicket.analyze() # do whatever you do to fix it?! aTicket.status = aTicket.analyze() # check if its fixed return aTicket.status > The only solution I can think of here is having the main function > (in > main.py) which instantiates all these objects actually *pass in* to > the codemonkey and reviewer the reference to the specific objects > ticketAnalyzer and ticket. Is this the best way to do it? Its one approach. Without knowing a lot more about the problem it seems a reasonable way forward > handle that behavior in the __init__ of code{monkey,reviewer}? Almost certainly not. the monkey and reviewer will presumably work on more than one ticket so you want to feed the work in progressively rather than create new instances for each ticket - I assume, maybe not! You don't say much about what the system does, which is pretty fundamental to OOD since it is driven by the behaviour required. I'm guessing that you want to be able to create multiple tickets and assign them to a group of monkeys and reviewers? The system then manages the progress of the tickets? > I instead create a method inside of the codemonkey and reviewer > classes that accepts the object pointer to the ticket objects and > then > interact between ticket/code* objects as such? That's the way I'd go. OOP programs are all about objects interacting. Think of the main function as being the global controller kicking off the initial scenarios which then run as semi-autonomous threads. > I image it would be much easier to have everything in one file, but > that goes against my grain. ;) As I said earlier the physical location of the code makes no difference to the logical design of the system. A few import startements will deal with that. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Aug 2 19:00:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 18:00:30 +0100 Subject: [Tutor] Why use lambda? References: <mailman.53.1217671217.6603.tutor@python.org> <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> Message-ID: <g723np$9nd$1@ger.gmane.org> "desmond mansfield" <desm at hotmail.co.uk> wrote > But what I don't understand, and cannot seem to find an > answer to, is why I'd actually want to use it ? Its a matter of taste. There is nothing you can do with lambda that you cannot do with a function definition. But you might need an awful lot of functions which can make your code cluttered. > What can lambda do that normal function definitions cannot? Exist without a name. > Is it quicker to execute/less memory intensive? No. > Or is it just quicker to type and easier to think about? Quicker to type but most folks don't find them easier to think about! The exception to that is people trained in Lambda calculus where lambdas are a fundamental part of the theory. Using lambdas then becomes the natural way to express a solution. Lambda calculus is what the Functional Programming style is based upon. Python supports FP so it has lambdas. You don't have to use them. Some other languages provide much stronger support for lambdas than does Python. The python community tends to be split into those who would like to see lanmdas made much more powerful and those who woyuld like to see them removed entirely! The current syntactic sugar version pleases nobody very much. :-) >From a pure FP theory point of view a function is a named lambda. In some dialects of Lisp you define a function by creating a lambda, like this: (defun f (lambda (expr))) In Python we can say that def f : return (expr) is identical to f = lambda: (expr) Ruby and Smalltalk both offer "code blocks" which perform the same function but with more flexibility. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Aug 2 19:04:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 18:04:00 +0100 Subject: [Tutor] removing whole numbers from text References: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> Message-ID: <g723uc$act$1@ger.gmane.org> "Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote > I want to remove whole numbers from text but retain numbers > attached to words. Is this a homework? If so we can only offer suggestions to direction but not give solutions. > What is the best to do this using re? Yes, use re to define a pattern then use sub() to replace with an empty string Alan G. -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Aug 2 19:08:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Aug 2008 18:08:44 +0100 Subject: [Tutor] I can't believe this needs to be this complex References: <20080802100759.4A97D1E4003@bag.python.org><1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> <20080802132734.A50001E4016@bag.python.org> Message-ID: <g72478$b31$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > BTW Kent, I'm going to take this opportunity to ask you about > "System" in the IPython timing results. It's always zero for the > code I time. What's an example of code that would have System be > greater than zero? And what's the distinction between User and > System? (I'm using Win XP, if that's relevant.) In timing user time is time that the CPU spends executing user code - your program. System time is time the CPU spends doing OS things. If your code had a blocking call that waited for input on a port say, then the OS might be doing other stuff in the background while your code waited. This would show as system time. In some OR even time spent reading files from disk is counted as system time because your code is executing low level OS functions. Try timing a function that does nothing but read a large file. See if there is any system time showing up. Or time a GUI app that waits for user input... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From noufal at nibrahim.net.in Sat Aug 2 20:02:50 2008 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sat, 02 Aug 2008 23:32:50 +0530 Subject: [Tutor] removing whole numbers from text In-Reply-To: <g723uc$act$1@ger.gmane.org> References: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> <g723uc$act$1@ger.gmane.org> Message-ID: <4894A14A.8060306@nibrahim.net.in> Alan Gauld wrote: > > "Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote > >> I want to remove whole numbers from text but retain numbers >> attached to words. > > Is this a homework? > If so we can only offer suggestions to direction but not give solutions. > >> What is the best to do this using re? > > Yes, use re to define a pattern then use sub() to replace with > an empty string If you're having trouble with writing regular expressions, you can either use http://www.weitz.de/regex-coach/ (Regex-coach) or Emacs re-builder mode for some interactive training. -- ~noufal http://nibrahim.net.in/ From jtp at nc.rr.com Sat Aug 2 20:36:00 2008 From: jtp at nc.rr.com (James) Date: Sat, 2 Aug 2008 14:36:00 -0400 Subject: [Tutor] locks and threads Message-ID: <e107b4ff0808021136p5238b508q6b6aefb03cf012e3@mail.gmail.com> All, I'm trying to write a class that will acquire a lock before entering a critical section, and then release it. Does this look like the right way to go about accomplishing my goal? try: grabLock = self.lock.acquire( 0 ) if grabLock: print 'acquired lock successfully' else: print "did *not* obtain lock" < ** what do I put here? ** > finally: if grabLock is True: <do something "critical" here> self.lock.release() print 'released lock' What should I be doing in the else: statement? If I can't grab the lock, should I simply try again? Maybe a while loop that keeps trying until I grab the lock? (I'm not really sure how I'm going to integrate the 'try' statement with the while loop, though, to solve the problem of not grabbing the lock) Thoughts? -j From benoit.thiell at cern.ch Sat Aug 2 21:01:26 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Sat, 2 Aug 2008 21:01:26 +0200 Subject: [Tutor] removing whole numbers from text In-Reply-To: <4894A14A.8060306@nibrahim.net.in> References: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> <g723uc$act$1@ger.gmane.org> <4894A14A.8060306@nibrahim.net.in> Message-ID: <alpine.DEB.1.10.0808022101050.3743@pcuds30> Dear Dinesh, if you're using the regular expression only once, I would recommend: without_numbers = " ".join(re.split(" [0-9]+ ", phrase)) If not, compile the regular expression first and use the compiled version. Regards, Benoit Thiell. On Sat, 2 Aug 2008, Noufal Ibrahim wrote: > Alan Gauld wrote: >> >> "Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote >> >>> I want to remove whole numbers from text but retain numbers >>> attached to words. >> >> Is this a homework? >> If so we can only offer suggestions to direction but not give solutions. >> >>> What is the best to do this using re? >> >> Yes, use re to define a pattern then use sub() to replace with >> an empty string > > > If you're having trouble with writing regular expressions, you can either use > http://www.weitz.de/regex-coach/ (Regex-coach) or Emacs re-builder mode for > some interactive training. > > > -- > ~noufal > http://nibrahim.net.in/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Sat Aug 2 22:17:51 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 02 Aug 2008 16:17:51 -0400 Subject: [Tutor] Why use lambda? In-Reply-To: <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> References: <mailman.53.1217671217.6603.tutor@python.org> <BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> Message-ID: <4894C0EF.7000604@gmail.com> desmond mansfield wrote: > I've read some small tutorials on lambda, and how I can use it to define functions "on-the-fly". > But what I don't understand, and cannot seem to find an answer to, is why I'd actually want to use it ? > > What can lambda do that normal function definitions cannot? > Is it quicker to execute/less memory intensive? > Or is it just quicker to type and easier to think about? In my Python Pipelines program for the Count stage I have: opts = { 'characters' : lambda rec, tot: tot + len(rec), 'words' : lambda rec, tot: tot + len(rec.split()), 'lines' : lambda rec, tot: tot + 1, 'minline' : lambda rec, tot: min(len(rec), tot), 'maxline' : lambda rec, tot: max(len(rec), tot), } Consider how many more lines of code it would take if I had to use defs. Consider how readable it is to have the expressions all in one place. -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Sun Aug 3 01:28:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 00:28:11 +0100 Subject: [Tutor] Why use lambda? References: <mailman.53.1217671217.6603.tutor@python.org><BLU104-W306A7285B66DC633893C0D8D7E0@phx.gbl> <4894C0EF.7000604@gmail.com> Message-ID: <g72qen$42q$1@ger.gmane.org> "bob gailer" <bgailer at gmail.com> wrote > In my Python Pipelines program for the Count stage I have: > > opts = { > 'characters' : lambda rec, tot: tot + len(rec), > 'words' : lambda rec, tot: tot + len(rec.split()), > 'lines' : lambda rec, tot: tot + 1, > 'minline' : lambda rec, tot: min(len(rec), tot), > 'maxline' : lambda rec, tot: max(len(rec), tot), > } def characters(rec,tot): return tot + len(rec) def words(rec,tot): return tot + len(rec.split()) etc... Not many more characters than using lambda and avoids the need for the dictionary lookup: instead of w = opts['words'](r,c) just use: w = words(r,c) If you need the dictionary for dynamic lookup then just insert the functions intop the dict: opts = { 'characters' : characters, 'worsds' : words, etc... } > Consider how many more lines of code it would take if I had to use > defs. More or less by definition a Python lambda expression can be replaced with a one-liner function. > Consider how readable it is to have the expressions all in one > place. In this case I'm not sure the gain is huge, its largely a matter of personal preference. Alan G. From alan.gauld at btinternet.com Sun Aug 3 01:35:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 00:35:20 +0100 Subject: [Tutor] Classes in separate files References: <e107b4ff0808020734v665b3395pb5d5e42de62c7c37@mail.gmail.com> <e107b4ff0808020751j98a95ddr5af13a60add84db9@mail.gmail.com> Message-ID: <g72qs4$4t5$1@ger.gmane.org> "James" <jtp at nc.rr.com> wrote > Another question on classes in separate files... It could just as well be about functions. The issue is about visibility of names not classes. > main.py instantiates a class called 'testClass' inside of a file > temp.py. > > In main.py: > t = temp.testClass() > ... > So here's a question...how does the object *t* (defined in the > temp.py > file) access a global (or even local) variable in main.py? Is it > possible? You would need to import main into temp.py. But thats OK since your code has to know about main to want to access one of its variables! But it destroys yuour classes reuse capability since they are now bound to main... Otherwise make it a parameter to the method and pass it in from where it is called in main. > What if I want the object t to write to a global variable > inside of main.py...is that possible? Same as above import the module. Or make the method returm the value and explicitly set the value. All of which emphasises why global variables are a bad design idea. And why class methods should work with their own internal data as much as possible. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From david at abbottdavid.com Sun Aug 3 04:14:27 2008 From: david at abbottdavid.com (David) Date: Sat, 02 Aug 2008 22:14:27 -0400 Subject: [Tutor] Output never stops Message-ID: <48951483.6020501@abbottdavid.com> Very new to python and never programed before. Can not figure out why the output never stops when I run this in a terminal #!/usr/bin/python choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") while choice != '-1': person = {'Lary': 43,'Joan': 24} if choice == 'Lary': print "Lary's age is:", person.get('Lary') elif choice == 'Joan': print "Joan's age is:", person.get('Joan') else: print 'Bad Code' -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From david at abbottdavid.com Sun Aug 3 04:21:33 2008 From: david at abbottdavid.com (David) Date: Sat, 02 Aug 2008 22:21:33 -0400 Subject: [Tutor] Output never stops In-Reply-To: <48951483.6020501@abbottdavid.com> References: <48951483.6020501@abbottdavid.com> Message-ID: <4895162D.5010803@abbottdavid.com> David wrote: > Very new to python and never programed before. Can not figure out why > the output never stops when I run this in a terminal > > > #!/usr/bin/python > > > choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") > while choice != '-1': person = {'Lary': 43,'Joan': 24} > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > > else: > print 'Bad Code' > should have been like this; #!/usr/bin/python choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") while choice != '-1': person = {'Lary': 43,'Joan': 24} if choice == 'Lary': print "Lary's age is:", person.get('Lary') elif choice == 'Joan': print "Joan's age is:", person.get('Joan') else: print 'Bad Code' -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From vsant at hcs.harvard.edu Sun Aug 3 04:50:22 2008 From: vsant at hcs.harvard.edu (Vivek Sant) Date: Sat, 2 Aug 2008 22:50:22 -0400 Subject: [Tutor] Output never stops In-Reply-To: <4895162D.5010803@abbottdavid.com> References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> Message-ID: <6B8E91B8-CBD1-46FC-A1A7-C511501BDEB4@hcs.harvard.edu> Hi David, Simple explanation - you should use if instead of while. A while statement executes whatever is in that block again and again until the condition becomes false. So your code, the way you have it, first checks if the user's input is not -1. If you have typed Lary, it goes on to print Lary, hits the end of the while block, and starts back at the top, since choice still is not -1. If you change while to if, the statement will only be executed once. Here's a scenario you might want to use a while loop (which might be what you were trying to do): suppose you want to keep on asking for input if the input is not a quit code, or valid input. To do this, you could just put the choice = raw_input line inside the while block, and perhaps make sure to initialize choice to '' (an empty string or something). Vivek On Aug 2, 2008, at 10:21 PM, David wrote: > David wrote: >> Very new to python and never programed before. Can not figure out >> why the output never stops when I run this in a terminal >> >> >> #!/usr/bin/python >> >> >> choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") >> while choice != '-1': person = {'Lary': 43,'Joan': 24} >> if choice == 'Lary': >> print "Lary's age is:", person.get('Lary') >> >> elif choice == 'Joan': >> print "Joan's age is:", person.get('Joan') >> >> else: >> print 'Bad Code' >> > should have been like this; > > #!/usr/bin/python > > > choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") > while choice != '-1': person = {'Lary': 43,'Joan': 24} > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > > else: > print 'Bad Code' > > > -- > Powered by Gentoo GNU/LINUX > http://www.linuxcrazy.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From federo at email.si Sat Aug 2 16:39:53 2008 From: federo at email.si (Federo) Date: Sat, 02 Aug 2008 16:39:53 +0200 Subject: [Tutor] Developing Macro: Is it possible in Python? Message-ID: <20080802143954.3159C8D183@www1.email.si> Hi Is it possible to do macro with Python? Macro should be able to click on given x,y screen location (one click, double click), drag scroll bar up / down etc.. Macro should be also able to extract data from predefined screen x,y location. I would use this to control desktop windows based program. The program is written from external provider - not Microsoft or me (it runs on xp environment).. Above actions can be easily performed using Macro Scheduler. I am looking for possibility to do the same with Python? Is there any other way beside macro to control windows based application? The best will be to be able to control application from background (the same time mouse and screen would be free for other work. No flashing on screen. In ideal program would be ran as beck - hiden process..) Cheers, Fedo ____________________ http://www.email.si/ From federo at email.si Sat Aug 2 17:17:48 2008 From: federo at email.si (Federo) Date: Sat, 02 Aug 2008 17:17:48 +0200 Subject: [Tutor] Firstrade URL Authentication? In-Reply-To: <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> References: <20080801073939.974DC8CEF6@www1.email.si> <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> Message-ID: <20080802151749.D7F6B8DEA1@www1.email.si> Hi Kent Thanks for your reply. According to your instruction I have tried in Python interactive window the following (in my test I have used real username and password): >>> import urllib2 >>> import urllib >>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) >>> urllib2.install_opener(opener) >>> params = urllib.urlencode(dict(username='user', password='pass')) >>> f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) >>> data = f.read() >>> f.close() >>> f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do') >>> data = f.read() >>> print(data) It printed out login page which means I wasn't able to login to the main page. There must be some sofisticated trick to login to www.Firstrade.com. Any Idea what else can I try? Cheers, Fedo On Fri, 1 Aug 2008 at 12:45:47, Kent Johnson wrote: > On Fri, Aug 1, 2008 at 3:39 AM, Federo <federo at email.si> wrote: > > Hi .. > > > > I have to admit that Python is really surprising me. It was lucky day a > few > > weeks ago I firts time start using Python. Lot's of things realy can be > done > > with short learning curve. Your user guieds was best place to start! > > > > Below is problem I am unable to solve. I would appreciate your advice or > > even better code sample. The problem is URL authorisation. > > I have a writeup on form-based authentication here: > http://personalpages.tds.net/~kent37/kk/00010.html#e10form-based-authenticati > on > > Kent ____________________ http://www.email.si/ From kent37 at tds.net Sun Aug 3 05:32:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 23:32:09 -0400 Subject: [Tutor] Firstrade URL Authentication? In-Reply-To: <20080802151749.D7F6B8DEA1@www1.email.si> References: <20080801073939.974DC8CEF6@www1.email.si> <1c2a2c590808010341v486b4a21if0b2f59d8b8367e8@mail.gmail.com> <20080802151749.D7F6B8DEA1@www1.email.si> Message-ID: <1c2a2c590808022032v5c4ef486r4084f215273fa4e4@mail.gmail.com> On Sat, Aug 2, 2008 at 11:17 AM, Federo <federo at email.si> wrote: > There must be some sofisticated trick to login to www.Firstrade.com. Any Idea > what else can I try? You have to find out what it does in the browser using Firebug or other tools that will let you see the headers and data. Perhaps there is another cookie (Django authentication sends a cookie with the login form). Perhaps there is some other header that must be set. Look for other cookies and try setting the User-Agent header to match what the browser sends, or just match all the headers. Kent From kent37 at tds.net Sun Aug 3 05:38:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Aug 2008 23:38:50 -0400 Subject: [Tutor] locks and threads In-Reply-To: <e107b4ff0808021136p5238b508q6b6aefb03cf012e3@mail.gmail.com> References: <e107b4ff0808021136p5238b508q6b6aefb03cf012e3@mail.gmail.com> Message-ID: <1c2a2c590808022038u7f3d568v7e913840d2a6dd23@mail.gmail.com> On Sat, Aug 2, 2008 at 2:36 PM, James <jtp at nc.rr.com> wrote: > All, > > I'm trying to write a class that will acquire a lock before entering a > critical section, and then release it. Does this look like the right > way to go about accomplishing my goal? > > try: > grabLock = self.lock.acquire( 0 ) > if grabLock: > print 'acquired lock successfully' > else: > print "did *not* obtain lock" > < ** what do I put here? ** > > finally: > if grabLock is True: > > <do something "critical" here> > self.lock.release() > print 'released lock' > > What should I be doing in the else: statement? If I can't grab the > lock, should I simply try again? Maybe a while loop that keeps trying > until I grab the lock? (I'm not really sure how I'm going to integrate > the 'try' statement with the while loop, though, to solve the problem > of not grabbing the lock) What are you using for the lock. A threading.Lock will block if you try to acquire it and it is not available. Why do you need the try? You could put the acquire in a while loop. You probably want to sleep in the loop, so you don't chew up too much CPU. Kent From rdm at rcblue.com Sun Aug 3 06:11:41 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Aug 2008 21:11:41 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <g72478$b31$1@ger.gmane.org> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> <20080802132734.A50001E4016@bag.python.org> <g72478$b31$1@ger.gmane.org> Message-ID: <20080803041156.34ED71E4006@bag.python.org> At 10:08 AM 8/2/2008, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > >>BTW Kent, I'm going to take this opportunity to ask you about >>"System" in the IPython timing results. It's always zero for the >>code I time. What's an example of code that would have System be >>greater than zero? And what's the distinction between User and >>System? (I'm using Win XP, if that's relevant.) > >In timing user time is time that the CPU spends executing user >code - your program. System time is time the CPU spends doing >OS things. > >If your code had a blocking call that waited for input on a port say, >then the OS might be doing other stuff in the background while >your code waited. This would show as system time. >In some OR even time spent reading files from disk is >counted as system time because your code is executing >low level OS functions. > >Try timing a function that does nothing but read a large file. >See if there is any system time showing up. Well, here's one that reads in the text of Dickens' _Little Dorrit_ and returns the word count: In [11]: run -t -N10 timing_test_little_dorrit.py 339832 339832 339832 339832 339832 339832 339832 339832 339832 339832 IPython CPU timings (estimated): Total runs performed: 10 Times : Total Per run User : 5.94446752311 s, 0.594446752311 s. System: 0.0 s, 0.0 s. >Or time a GUI >app that waits for user input... This one is a Gui that has an Exit button. I called it and then hit the button: In [4]: run -t ToolkitV15.py IPython CPU timings (estimated): User : 10.5294301371 s. System: 0.0 s. So no non-zero System time yet. But thanks for your explanation. Dick From alan.gauld at btinternet.com Sun Aug 3 10:00:29 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 09:00:29 +0100 Subject: [Tutor] I can't believe this needs to be this complex References: <20080802100759.4A97D1E4003@bag.python.org><1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com><1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m><20080802132734.A50001E4016@bag.python.org><g72478$b31$1@ger.gmane.org> <20080803041156.34ED71E4006@bag.python.org> Message-ID: <g73ofa$p6t$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote >>>code I time. What's an example of code that would have System be >>>greater than zero? And what's the distinction between User and >>>System? (I'm using Win XP, if that's relevant.) It may be that XP doesn't report System time. > Well, here's one that reads in the text of Dickens' _Little Dorrit_ > and returns the word count: > > IPython CPU timings (estimated): > Total runs performed: 10 > Times : Total Per run > User : 5.94446752311 s, 0.594446752311 s. > System: 0.0 s, 0.0 s. I would definitely have expected some system time there. > This one is a Gui that has an Exit button. I called it and then hit > the button: > > IPython CPU timings (estimated): > User : 10.5294301371 s. > System: 0.0 s. That suggests that it is counting elapsed time as user time in which case I'm not sure how it counts system time. It may be an XP issue. Anyone got different results under Linux/MacOS? Alan G. From alan.gauld at btinternet.com Sun Aug 3 10:06:52 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 09:06:52 +0100 Subject: [Tutor] Developing Macro: Is it possible in Python? References: <20080802143954.3159C8D183@www1.email.si> Message-ID: <g73or8$q1u$1@ger.gmane.org> "Federo" <federo at email.si> wrote > Is it possible to do macro with Python? Macro means different things in different context. > Macro should be able to click on given x,y screen > location (one click, double click), drag scroll bar up / down etc.. It seems that you are referring to simulating user actions. The answer then is yes its possible but not trivial. You can use the low level Windows API to send messages to windows simulating mouse clicks etc. But it will usually require monitoring the messages first using a program like Windows Spy. The result is extremely fragile in that any change in the windows environment can render your code useless. > Is there any other way beside macro to control windows > based application? If it supports COM then you can use COM objects to manipulate things directly. The winall package has support for COM or you can use the API directly via ctypes. I confess I tend to use VBScript for this kind of thing, IMHO it plays with Windows much more simply than Python. Alan G. From alan.gauld at btinternet.com Sun Aug 3 10:12:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 09:12:35 +0100 Subject: [Tutor] Output never stops References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> Message-ID: <g73p5v$qqf$1@ger.gmane.org> "David" <david at abbottdavid.com> wrote >> the output never stops when I run this in a terminal >> > choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") > while choice != '-1': > person = {'Lary': 43,'Joan': 24} > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > else: > print 'Bad Code' You set choice outside the while loop then never change it so the while test will always be true and loop forever. You need to copy the raw_input line into the body of the while loop to reset choice. Also for good style you should move the person = {} line outside the loop since you only want to set up the dictionary once, not every time you execute the loop. The dictionary never changes so recreating it every time is wasteful. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sun Aug 3 13:19:35 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Aug 2008 04:19:35 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <g73ofa$p6t$1@ger.gmane.org> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.co m> <20080802132734.A50001E4016@bag.python.org> <g72478$b31$1@ger.gmane.org> <20080803041156.34ED71E4006@bag.python.org> <g73ofa$p6t$1@ger.gmane.org> Message-ID: <20080803111950.2BA9A1E4002@bag.python.org> At 01:00 AM 8/3/2008, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > >>>>code I time. What's an example of code that would have System be >>>>greater than zero? And what's the distinction between User and >>>>System? (I'm using Win XP, if that's relevant.) > >It may be that XP doesn't report System time. > >>Well, here's one that reads in the text of Dickens' _Little Dorrit_ >>and returns the word count: >> >>IPython CPU timings (estimated): >>Total runs performed: 10 >> Times : Total Per run >> User : 5.94446752311 s, 0.594446752311 s. >> System: 0.0 s, 0.0 s. > >I would definitely have expected some system time there. > >>This one is a Gui that has an Exit button. I called it and then hit >>the button: >> >>IPython CPU timings (estimated): >> User : 10.5294301371 s. >> System: 0.0 s. > >That suggests that it is counting elapsed time as user time >in which case I'm not sure how it counts system time. >It may be an XP issue. > >Anyone got different results under Linux/MacOS? _Little Dorrit_ is available in us-ascii at <http://www.gutenberg.org/etext/963>; _War and Peace_ at <http://www.gutenberg.org/etext/2600>. Dick From kent37 at tds.net Sun Aug 3 14:15:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Aug 2008 08:15:01 -0400 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <g73ofa$p6t$1@ger.gmane.org> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <20080802132734.A50001E4016@bag.python.org> <g72478$b31$1@ger.gmane.org> <20080803041156.34ED71E4006@bag.python.org> <g73ofa$p6t$1@ger.gmane.org> Message-ID: <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.com> On Sun, Aug 3, 2008 at 4:00 AM, Alan Gauld <alan.gauld at btinternet.com> wrote: > "Dick Moores" <rdm at rcblue.com> wrote > >>>> code I time. What's an example of code that would have System be greater >>>> than zero? And what's the distinction between User and System? (I'm using >>>> Win XP, if that's relevant.) > > It may be that XP doesn't report System time. >From the IPython help for 'run': -t: print timing information at the end of the run. IPython will give you an estimated CPU time consumption for your script, which under Unix uses the resource module to avoid the wraparound problems of time.clock(). Under Unix, an estimate of time spent on system tasks is also given (for Windows platforms this is reported as 0.0). Kent From cniall at icedcerulean.com Sun Aug 3 16:04:09 2008 From: cniall at icedcerulean.com (CNiall) Date: Sun, 03 Aug 2008 15:04:09 +0100 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) Message-ID: <4895BAD9.5010004@icedcerulean.com> I am very new to Python (I started learning it just yesterday), but I have encountered a problem. I want to make a simple script that calculates the n-th root of a given number (e.g. 4th root of 625--obviously five, but it's just an example :P), and because there is no nth-root function in Python I will do this with something like x**(1/n). However, with some, but not all, decimals, they do not seem to 'equal themselves'. This is probably a bad way of expressing what I mean, so I'll give an example: >>> 0.5 0.5 >>> 0.25 0.25 >>> 0.125 0.125 >>> 0.2 0.20000000000000001 >>> 0.33 0.33000000000000002 As you can see, the last two decimals are very slightly inaccurate. However, it appears that when n in 1/n is a power of two, the decimal does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not 0.20000000000000001? This discrepancy is very minor, but it makes the whole n-th root calculator inaccurate. :\ From rdm at rcblue.com Sun Aug 3 17:30:42 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Aug 2008 08:30:42 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <20080802132734.A50001E4016@bag.python.org> <g72478$b31$1@ger.gmane.org> <20080803041156.34ED71E4006@bag.python.org> <g73ofa$p6t$1@ger.gmane.org> <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.com> Message-ID: <20080803153054.705E81E4002@bag.python.org> At 05:15 AM 8/3/2008, Kent Johnson wrote: >On Sun, Aug 3, 2008 at 4:00 AM, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "Dick Moores" <rdm at rcblue.com> wrote > > > >>>> code I time. What's an example of code that would have System be greater > >>>> than zero? And what's the distinction between User and System? > (I'm using > >>>> Win XP, if that's relevant.) > > > > It may be that XP doesn't report System time. > > From the IPython help for 'run': > > -t: print timing information at the end of the run. IPython will >give you an estimated CPU time consumption for your script, which >under Unix uses the resource module to avoid the wraparound >problems of time.clock(). Under Unix, an estimate of time spent on >system tasks is also given Thanks, Kent. RTFM! >(for Windows platforms this is reported >as 0.0). I wonder why it is reported for Windows at all? Dick From rdm at rcblue.com Sun Aug 3 17:30:42 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 03 Aug 2008 08:30:42 -0700 Subject: [Tutor] I can't believe this needs to be this complex In-Reply-To: <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.co m> References: <20080802100759.4A97D1E4003@bag.python.org> <1c2a2c590808020502u683edc88h8eef27a25060b0d9@mail.gmail.com> <20080802132734.A50001E4016@bag.python.org> <g72478$b31$1@ger.gmane.org> <20080803041156.34ED71E4006@bag.python.org> <g73ofa$p6t$1@ger.gmane.org> <1c2a2c590808030515l4ac4fe58n41bf19c9669d1a4a@mail.gmail.com> Message-ID: <20080803153054.73F471E4003@bag.python.org> At 05:15 AM 8/3/2008, Kent Johnson wrote: >On Sun, Aug 3, 2008 at 4:00 AM, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "Dick Moores" <rdm at rcblue.com> wrote > > > >>>> code I time. What's an example of code that would have System be greater > >>>> than zero? And what's the distinction between User and System? > (I'm using > >>>> Win XP, if that's relevant.) > > > > It may be that XP doesn't report System time. > > From the IPython help for 'run': > > -t: print timing information at the end of the run. IPython will >give you an estimated CPU time consumption for your script, which >under Unix uses the resource module to avoid the wraparound >problems of time.clock(). Under Unix, an estimate of time spent on >system tasks is also given Thanks, Kent. RTFM! >(for Windows platforms this is reported >as 0.0). I wonder why it is reported for Windows at all? Dick From thomas.pani at gmail.com Sun Aug 3 17:32:27 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Sun, 03 Aug 2008 17:32:27 +0200 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) In-Reply-To: <4895BAD9.5010004@icedcerulean.com> References: <4895BAD9.5010004@icedcerulean.com> Message-ID: <4895CF8B.3050203@gmail.com> CNiall wrote: > I want to make a simple script that calculates the n-th root of a given > number (e.g. 4th root of 625--obviously five, but it's just an example > :P), and because there is no nth-root function in Python I will do this > with something like x**(1/n). > Side note: of course there are python built-in ways to do that. You just named one yourself: In [6]: 625**(1.0/4) Out[6]: 5.0 also: In [9]: pow(625, 1.0/4) Out[9]: 5.0 > However, with some, but not all, decimals, they do not seem to 'equal > themselves'. > > As you can see, the last two decimals are very slightly inaccurate. > However, it appears that when n in 1/n is a power of two, the decimal > does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 > and not 0.20000000000000001? > You just can't store 0.1 as a binary floating point. You might want to read: http://www.network-theory.co.uk/docs/pytut/FloatingPointArithmeticIssuesandLimitations.html http://www.network-theory.co.uk/docs/pytut/RepresentationError.html The decimal module provides decimal floating point arithmetic: http://docs.python.org/lib/module-decimal.html like in: In [1]: 0.2 * 2 Out[1]: 0.40000000000000002 In [2]: from decimal import Decimal In [3]: Decimal('0.2') * 2 Out[3]: Decimal("0.4") thomas From david at abbottdavid.com Sun Aug 3 17:33:15 2008 From: david at abbottdavid.com (David) Date: Sun, 03 Aug 2008 11:33:15 -0400 Subject: [Tutor] Output never stops In-Reply-To: <g73p5v$qqf$1@ger.gmane.org> References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> <g73p5v$qqf$1@ger.gmane.org> Message-ID: <4895CFBB.1070601@abbottdavid.com> Alan Gauld wrote: > > "David" <david at abbottdavid.com> wrote >>> the output never stops when I run this in a terminal >>> >> choice = raw_input("Enter the name Lary or Joan (-1 to quit): ") >> while choice != '-1': person = {'Lary': 43,'Joan': 24} >> if choice == 'Lary': >> print "Lary's age is:", person.get('Lary') >> elif choice == 'Joan': >> print "Joan's age is:", person.get('Joan') >> else: >> print 'Bad Code' > > You set choice outside the while loop then never change it so the > while test will always be true and loop forever. > You need to copy the raw_input line into the body of the while loop to > reset choice. > > Also for good style you should move the person = {} line outside the > loop since you only want to set up the dictionary once, not every time > you execute the loop. The dictionary never changes so recreating it > every time is wasteful. > > HTH, > Thanks Alan, also your tutorial/book is a big help. I think I got it :) #!/usr/bin/python person = {'Lary':43,'Joan':24} choice = 0 while choice != '-1': if choice == '': print "You must enter Lary or Joan to continue! (-1 to quit): " choice = raw_input( "Who's age do want to know, Lary or Joan? (-1 to quit): ") if choice == 'Lary': print "Lary's age is:", person.get('Lary') elif choice == 'Joan': print "Joan's age is:", person.get('Joan') else: print "Goodbye!" -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From kent37 at tds.net Sun Aug 3 17:35:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Aug 2008 11:35:49 -0400 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) In-Reply-To: <4895BAD9.5010004@icedcerulean.com> References: <4895BAD9.5010004@icedcerulean.com> Message-ID: <1c2a2c590808030835r1dd8f52bq2d32f57e6dc6edc2@mail.gmail.com> On Sun, Aug 3, 2008 at 10:04 AM, CNiall <cniall at icedcerulean.com> wrote: > I want to make a simple script that calculates the n-th root of a given > number (e.g. 4th root of 625--obviously five, but it's just an example :P), > and because there is no nth-root function in Python I will do this with > something like x**(1/n). > > However, with some, but not all, decimals, they do not seem to 'equal > themselves'. This is probably a bad way of expressing what I mean, so I'll > give an example: > 0.125 >>>> 0.2 > 0.20000000000000001 >>>> 0.33 > 0.33000000000000002 > > As you can see, the last two decimals are very slightly inaccurate. However, > it appears that when n in 1/n is a power of two, the decimal does not get > 'thrown off'. How might I make Python recognise 0.2 as 0.2 and not > 0.20000000000000001? This is a limitation of floaating point numbers. A discussion is here: http://docs.python.org/tut/node16.html Your root calculator can only find answers that are as accurate as the representation allows. Kent From alan.gauld at btinternet.com Sun Aug 3 17:44:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Aug 2008 16:44:46 +0100 Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals0.200000001) References: <4895BAD9.5010004@icedcerulean.com> Message-ID: <g74jlr$r5b$1@ger.gmane.org> "CNiall" <cniall at icedcerulean.com> wrote > However, with some, but not all, decimals, they do not seem to > 'equal themselves'. This is probably a bad way of expressing what I > mean, so I'll give an example: > >>> 0.5 > 0.5 > >>> 0.2 > 0.20000000000000001 > As you can see, the last two decimals are very slightly inaccurate. > However, it appears that when n in 1/n is a power of two, the > decimal does not get 'thrown off'. And that is the clue. Computers represent data as binary, ie powers of two. If a number cannot be expressed exactly as a power of two then a computer (any binary computer!) cannot represent the number exactly. It is the same in "natural" arithmetic where we use base 10. We cannot exactly represent numbers like 1/3 as a decimal number we have to approximate to 0.33333333.... Likewise with 1/7 etc. In most cases the approximation is "good enough" and we just live with it. (But its not a good idea to use floating point numbers to represent money!). If you do need exact numbers you can use the decimal module which will do what you want but at the expense of adding complexity. > How might I make Python recognise 0.2 as 0.2 and not > 0.20000000000000001? Mostl;y it won;t matter, what you will want is to be able to print it as 0.2. You can do this in a number of ways but the most flexible is to use a format string: >>> x = 0.2 >>> print "%6f" % x 0.2000 The percent inside the string is a marker which is substituted by the value after the percent outside the string (ie x in this case) The number following the first % is the length of representation - 6 chars in this case. There are several other numbers and symbols you can use to coerce the representation to be as you wish - left/roight aligned, leading zeros, scientific notation etc Search the Python docs for "format" and you should find the details... The other thing to watch is when comparing float values. >>> y = 1 - 0.8 >>> y == x False >>> e = 0.0000000001 >>> x-e < y < x+e True You can find out more about format stringsin the Simple Sequences topic of my tutorial. You can find out a little bit more about floating point numbers in the Raw Data topic of my tutorial under the heading Real Numbers. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ptmcg at austin.rr.com Sun Aug 3 17:41:30 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 3 Aug 2008 10:41:30 -0500 Subject: [Tutor] Developing Macro: Is it possible in Python? In-Reply-To: <mailman.10868.1217751065.920.tutor@python.org> References: <mailman.10868.1217751065.920.tutor@python.org> Message-ID: <72D8C9397E8345E0A71D28B66C16EFDD@AWA2> I have used pywinauto for such tasks in the past. http://pywinauto.openqa.org/ In my case, I used pywinauto to automate mouse clicks on a browser in order to auto-play a Flash game running in the browser. I had to use PIL to take screenshots and then process images to "read" the screen. -- Paul From emile at fenx.com Sun Aug 3 18:20:23 2008 From: emile at fenx.com (Emile van Sebille) Date: Sun, 03 Aug 2008 09:20:23 -0700 Subject: [Tutor] Developing Macro: Is it possible in Python? In-Reply-To: <20080802143954.3159C8D183@www1.email.si> References: <20080802143954.3159C8D183@www1.email.si> Message-ID: <g74log$1ev$1@ger.gmane.org> Federo wrote: <snip> > Above actions can be easily performed using Macro Scheduler. I am looking for > possibility to do the same with Python? Hi Federo, I regularly combine Macro Scheduler with python by having my python code write mSched scripts. I find the combination of the two particularly adept at controlling legacy windows apps on current windows platforms. The main function accepts a command list and name, writes a .scp msched script file and invokes the mSched command with os.system. When I first considered how to approach this in about 2002, I looked at Mark Hammonds extensions and tried that, but it seemed to me at the time that the older apps simply didn't play nice and I fought harder to implement a pure python solution than the problem deserved. Now, it's easy to review the python created msched scripts and 'follow along' to catch the odd bug. mSched's capabilities have grown over that time as well and added some commands that make timing issues more predictable. Although, I admit I'm never actually in the mSched environment so I may well be doing things with python that are entirely doable in mSched. But, with python as glue I can control and coordinate as many disparate environments as the solution requires and it's mostly quick and easy. Emile From kent37 at tds.net Sun Aug 3 23:04:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Aug 2008 17:04:39 -0400 Subject: [Tutor] Firstrade Authentication ... In-Reply-To: <20080803164558.A7EB4981F4@www1.email.si> References: <20080803164558.A7EB4981F4@www1.email.si> Message-ID: <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> On Sun, Aug 3, 2008 at 12:45 PM, Federo <federo at email.si> wrote: > Jeff, Kent Hi! > > If possible I would most appreciate to use mechanize approach Jeff suggested. > Python plagin: http://wwwsearch.sourceforge.net/mechanize/ This seems to get to the "Thank you for applying for a Firstrade account." page: import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet500', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() print(data) Differences from your code: - Does a GET on the login page - the session cookie is set here, not on the POST - Includes all the form parameters Kent PS Please respond to the list, not to me personally. From zack_holden at hotmail.com Mon Aug 4 00:16:13 2008 From: zack_holden at hotmail.com (zack holden) Date: Sun, 3 Aug 2008 22:16:13 +0000 Subject: [Tutor] newbie: write ArcGIS lists to file? Message-ID: <BAY125-W492673361C031D884F59187790@phx.gbl> Dear List, This is my first time on the list, and my first run at Python, please forgive my ignorance. I'm trying to use Python to access ArcGIS modules in order to perform the same task on multiple files in a folder. I'm able to access a set of files via: import arcgisscripting, string gp = arcgisscripting.create() gp.Workspace = "E:/data" rasterSelect = [] rasterList = gp.ListRasters("", "tif") raster = rasterList.Next() while raster: if raster.endswith("_dt.tif"): print raster rasterSelect.append(raster) raster = rasterList.Next() This produces a list of all the files I have in my folder. I need to begin producing .csv files of this list that I can access using other programs. Would someone be willing to post a few lines of code showing me how to write the list the code above creates to an external file? Gratefully, Zack From python-list at puzzled.xs4all.nl Mon Aug 4 00:24:37 2008 From: python-list at puzzled.xs4all.nl (Patrick) Date: Mon, 04 Aug 2008 00:24:37 +0200 Subject: [Tutor] Firstrade Authentication ... In-Reply-To: <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> Message-ID: <48963025.6020709@puzzled.xs4all.nl> Kent Johnson wrote: [snip] > params = dict(username='janezfedero', password='kmet500', destination='') I hope this is a fake username & password.... Regards, Patrick From alan.gauld at freenet.co.uk Mon Aug 4 00:55:09 2008 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 3 Aug 2008 23:55:09 +0100 Subject: [Tutor] Any Italian speakers? Message-ID: <8635291937C04629B8D8AB50677E206E@xp> I received this message which Google tells me is Italian but then only gives a partial translation... Can anyone help? ------------------- voglio chiderti solo 1 cosa ... ma secondo te qualle e il miglior programma X programmare??? grazie ... da Cristian ----------------- Alan G. From alan.gauld at btinternet.com Mon Aug 4 01:08:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 00:08:35 +0100 Subject: [Tutor] Output never stops References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com><g73p5v$qqf$1@ger.gmane.org> <4895CFBB.1070601@abbottdavid.com> Message-ID: <g75dm0$2lq$1@ger.gmane.org> "David" <david at abbottdavid.com> wrote > Thanks Alan, also your tutorial/book is a big help. I think I got it > :) Close but not quite there yet. > choice = 0 > while choice != '-1': > if choice == '': > print "You must enter Lary or Joan to continue! (-1 to quit): > " > choice = raw_input( > "Who's age do want to know, Lary or Joan? (-1 to quit): > ") > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > else: > print "Goodbye!" Consider what happens if I enter a blank name. You print Goodbye but then go round the loop again prompting for another choice. You probably want the Goodbye to only be printed if choice == '-1'? And the test for the empty string should ptrobably be after you ask for the input? Also the normal way to access a dictionary value is to use square brackets: person['Lary'] get() does have the advantage that you can add a default value that is returned if the key doesn't exist. But that's not relevant in this case. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carlos.laviola at gmail.com Mon Aug 4 01:12:52 2008 From: carlos.laviola at gmail.com (Carlos Laviola) Date: Sun, 03 Aug 2008 20:12:52 -0300 Subject: [Tutor] List elements as indices to another list Message-ID: <48963B74.9000009@gmail.com> Hi, I have a simple "matrix" (nested list) defined as such: M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] I'm trying to come up with a different way of getting its, well, "reverse antidiagonal", since the actual antidiagonal of M goes from M[0, N] to M[N, 0] according to http://planetmath.org/encyclopedia/AntiDiagonalMatrix.html: j = 0 for i in range(len(M)-1, -1, -1): print M[i][j] j += 1 This works fine, but I was looking for a different solution, just for kicks, and came across something interesting. I can do: >>> i, j = range(len(M)), range(len(M)-1, -1, -1) >>> i [0, 1, 2] >>> j [2, 1, 0] Theoretically, I could then just iterate over range(len(M)) and grab M[i[N]j[N]], but that's not legal. What would be the right way of doing this? Thanks in advance, Carlos From alan.gauld at btinternet.com Mon Aug 4 01:13:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 00:13:02 +0100 Subject: [Tutor] newbie: write ArcGIS lists to file? References: <BAY125-W492673361C031D884F59187790@phx.gbl> Message-ID: <g75dub$3co$1@ger.gmane.org> "zack holden" <zack_holden at hotmail.com> wrote > I need to begin producing .csv files of this list that I can > access using other programs. > > Would someone be willing to post a few lines of code > showing me how to write the list the code above creates to an > external file? Check the documentation for the csv module, I beliebe it supports both reading and writing CSV files. Alan G. From alan.gauld at btinternet.com Mon Aug 4 01:33:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 00:33:56 +0100 Subject: [Tutor] List elements as indices to another list References: <48963B74.9000009@gmail.com> Message-ID: <g75f5h$6ar$1@ger.gmane.org> "Carlos Laviola" <carlos.laviola at gmail.com> wrote >>>> i > [0, 1, 2] >>>> j > [2, 1, 0] > > Theoretically, I could then just iterate over range(len(M)) and grab > M[i[N]j[N]], but that's not legal. What would be the right way of > doing > this? M [ i[N] ] [ j[N] ] You just missed a couple of brackets... HTH, Alan G From kent37 at tds.net Mon Aug 4 16:04:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 10:04:07 -0400 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <20080804120536.7603E9B056@www1.email.si> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> Message-ID: <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> On Mon, Aug 4, 2008 at 8:05 AM, Federo <federo at email.si> wrote: > Kent THANKS! It works great also on real account .. > > Two important Sub-QUESTIONS: > > 1.) Look attached word file. It describes form fields I would like to fill in > and read server resoult.. You just have to mimic what the browser does. Use a Firefox plugin that shows you what is being submitted; TamperData is one. Then set the same fields in your code. > 2.) Could you do the same login logic also with MECHANIZE plagin. There are > some very usefull function in this plagin I might use. However I have No, I'm not familiar with mechanize. Kent From federo at email.si Mon Aug 4 14:05:35 2008 From: federo at email.si (Federo) Date: Mon, 04 Aug 2008 14:05:35 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> Message-ID: <20080804120536.7603E9B056@www1.email.si> Kent THANKS! It works great also on real account .. Two important Sub-QUESTIONS: 1.) Look attached word file. It describes form fields I would like to fill in and read server resoult.. 2.) Could you do the same login logic also with MECHANIZE plagin. There are some very usefull function in this plagin I might use. However I have to be able to login firts.. Plagin download: http://wwwsearch.sourceforge.net/mechanize/ Cheers, Fedo On Sun, 3 Aug 2008 at 23:16:02, Kent Johnson wrote: > On Sun, Aug 3, 2008 at 12:45 PM, Federo <federo at email.si> wrote: > > Jeff, Kent Hi! > > > > If possible I would most appreciate to use mechanize approach Jeff > suggested. > > Python plagin: http://wwwsearch.sourceforge.net/mechanize/ > > This seems to get to the "Thank you for applying for a Firstrade account." > page: > import urllib2 > import urllib > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) > urllib2.install_opener(opener) > f = opener.open('https://investor.firstrade.com/firstrade/login.do') > data = f.read() > f.close() > > params = dict(username='janezfedero', password='kmet500', destination='') > params['login.x'] = 'Log+In' > params = urllib.urlencode(params) > f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) > data = f.read() > f.close() > print(data) > > Differences from your code: > - Does a GET on the login page - the session cookie is set here, not on the > POST > - Includes all the form parameters > > Kent > > PS Please respond to the list, not to me personally. ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement.doc Type: application/octet-stream Size: 53248 bytes Desc: FormManagement.doc URL: <http://mail.python.org/pipermail/tutor/attachments/20080804/ad91f46b/attachment-0001.obj> From tomazbevec at yahoo.com Mon Aug 4 17:32:53 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Mon, 4 Aug 2008 08:32:53 -0700 (PDT) Subject: [Tutor] Does unittest slow down code Message-ID: <757462.32952.qm@web32804.mail.mud.yahoo.com> Is code executed within a unit test significantly slower than code executed outside of a unit test? Does code executed within a unit test take up more memory? --TJB From kent37 at tds.net Mon Aug 4 17:53:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 11:53:14 -0400 Subject: [Tutor] Does unittest slow down code In-Reply-To: <757462.32952.qm@web32804.mail.mud.yahoo.com> References: <757462.32952.qm@web32804.mail.mud.yahoo.com> Message-ID: <1c2a2c590808040853p5c89cc9aka1de6d4048c55f17@mail.gmail.com> On Mon, Aug 4, 2008 at 11:32 AM, Tomaz Bevec <tomazbevec at yahoo.com> wrote: > > Is code executed within a unit test significantly slower than code executed outside of a unit test? Does code executed within a unit test take up more memory? Assuming you are asking about the unittest module...No, not unless you do something specific in the unit test, e.g. testing on a large data set would take more memory. Unittest just runs the code you tell it to and looks at the result. It doesn't instrument the code in any way. You do have to load the actual unittest module but I don't think it has any great memory requirements. Are you seeing this behaviour or just asking about it? Kent From Mike.Hansen at atmel.com Mon Aug 4 19:02:48 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Mon, 4 Aug 2008 11:02:48 -0600 Subject: [Tutor] Any Italian speakers? In-Reply-To: <8635291937C04629B8D8AB50677E206E@xp> References: <8635291937C04629B8D8AB50677E206E@xp> Message-ID: <7941B2693F32294AAF16C26B679A258D0324C62F@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Sunday, August 03, 2008 4:55 PM > To: tutor at python.org > Subject: [Tutor] Any Italian speakers? > > I received this message which Google tells me is Italian but then > only gives a partial translation... > > Can anyone help? > > ------------------- > voglio chiderti solo 1 cosa ... ma secondo te qualle e il > miglior programma X programmare??? > grazie ... > > da Cristian > ----------------- > > Alan G. Alan, Unfortunately, I only speak and read/write English. Did you find anyone to traslate? I plugged it into Bablefish and tried Italian to English and here's what I got.(Probably the same as you.). "I want chiderti only 1 thing... but according to you qualle and better program X to program? thanks " I also tried Spanish, Potuguese, and Greek, but the Italian one came out the best. Mike From bgailer at gmail.com Mon Aug 4 19:34:14 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 04 Aug 2008 13:34:14 -0400 Subject: [Tutor] Output never stops In-Reply-To: <4895CFBB.1070601@abbottdavid.com> References: <48951483.6020501@abbottdavid.com> <4895162D.5010803@abbottdavid.com> <g73p5v$qqf$1@ger.gmane.org> <4895CFBB.1070601@abbottdavid.com> Message-ID: <48973D96.5020607@gmail.com> David wrote: [snip] > #!/usr/bin/python > > person = {'Lary':43,'Joan':24} > > choice = 0 > while choice != '-1': > if choice == '': > print "You must enter Lary or Joan to continue! (-1 to quit): " > choice = raw_input( > "Who's age do want to know, Lary or Joan? (-1 to quit): ") > if choice == 'Lary': > print "Lary's age is:", person.get('Lary') > > elif choice == 'Joan': > print "Joan's age is:", person.get('Joan') > > else: > print "Goodbye!" > > Consider leveraging the dictionary (and some other"Pythonic" refinements). Separate the logic from the data. Now you can add more names and ages without changing the logic. #!/usr/bin/python person = {'Lary':43, 'Joan':24, 'Bob':68} keys = person.keys() names = ', '.join(keys[:-1]) + ' or ' + keys[-1] while True: choice = raw_input("Who's age do want to know, %s? (-1 to quit): " % names) age = person.get(choice, None) if age is not None: print choice + "'s age is:", age elif choice == "-1": print "Goodbye!" break else: print "Invalid choice " + choice -- Bob Gailer 919-636-4239 Chapel Hill, NC From ceasar102 at yahoo.com Mon Aug 4 20:04:45 2008 From: ceasar102 at yahoo.com (ammar azif) Date: Mon, 4 Aug 2008 11:04:45 -0700 (PDT) Subject: [Tutor] My experience on web.py Message-ID: <196711.50013.qm@web56813.mail.re3.yahoo.com> Hi, I am writing this to tell my experience on web.py. Two weeks ago, I was looking for a python web framework that is simple, straight-forward, easy to use and powerful at the same time. Django? stood out as the most popular when I googled. I tried to use django but I found that the framework hides alot of things from me and files are generated by the framework? automaticaly and I felt like I wasnt in control. I know that django is powerful, but the learning curve is too steep for me and? I need to develop my app as soon as possible. I decided to give web.py a try and I found that the framework is easy to use and it gives a lot of control to the developer when handling GET and POST request and all these can be done in a single source code and using this framework has taught me a lot of low level web application programming basics. I might be wrong as I havent try django or any other frameworks yet. Hope python gurus here can share their thoughts on these matters,? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080804/e5999521/attachment.htm> From optomatic at rogers.com Mon Aug 4 20:22:34 2008 From: optomatic at rogers.com (Patrick) Date: Mon, 04 Aug 2008 14:22:34 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <489748EA.1080508@rogers.com> I am in the same situation as you. I was looking at Django and Turbogears. I have finally settled on CherryPy, which is also built into Turbogears. Watching this Google talk on Youtube: http://www.youtube.com/watch?v=p-WXiqrzAf8 it seemed to me that Django is well suited for a developer team but is a bit sketchy when you try to scale it down to a single developer. CherryPy seems to work well as a substitute for all-in-one-page CGI scripts without the respawning issues or as a proper MVC web application server. I set up an account at Webfaction. They specialize in Python hosting and you can set up Turbogears, Django, CherryPy etc with a click of a button. I would love to keep this thread going, please feedback as you move along, I feedback too -patrick ammar azif wrote: > Hi, > > I am writing this to tell my experience on web.py. Two weeks ago, I > was looking for a python web framework that is simple, > straight-forward, easy to use and powerful at the same time. Django > stood out as the most popular when I googled. I tried to use django > but I found that the framework hides alot of things from me and files > are generated by the framework automaticaly and I felt like I wasnt > in control. I know that django is powerful, but the learning curve is > too steep for me and I need to develop my app as soon as possible. I > decided to give web.py a try and I found that the framework is easy to > use and it gives a lot of control to the developer when handling GET > and POST request and all these can be done in a single source code and > using this framework has taught me a lot of low level web application > programming basics. I might be wrong as I havent try django or any > other frameworks yet. Hope python gurus here can share their thoughts > on these matters, > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Aug 4 20:26:38 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Aug 2008 19:26:38 +0100 Subject: [Tutor] Any Italian speakers? References: <8635291937C04629B8D8AB50677E206E@xp> <7941B2693F32294AAF16C26B679A258D0324C62F@csomb01.corp.atmel.com> Message-ID: <g77hkv$3cj$1@ger.gmane.org> "Hansen, Mike" <Mike.Hansen at atmel.com> wrote > Did you find anyone to traslate? Yes thanks, Daniele (sp?) replied with a translation. There are some Italian idiomatic things there so it confused Google (and Babelfish!) > "I want chiderti only 1 thing... but according to you qualle > and better program X to program? thanks " Exactly what Google said... It seems the reader wants to know which is the best programming language... Thanks anyway, Alan G. From emile at fenx.com Mon Aug 4 20:34:04 2008 From: emile at fenx.com (Emile van Sebille) Date: Mon, 04 Aug 2008 11:34:04 -0700 Subject: [Tutor] My experience on web.py In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <g77hv8$4jn$1@ger.gmane.org> ammar azif wrote: <snip> > ... share their thoughts on these matters, I haven't tried web.py, but my experience with Django is the opposite of yours. Of course, I came to Django after climbing the learning curve of zope, so Django felt easy to deal with in comparison. It just seemed that each time I encountered a behavior that I wanted to change I could quickly locate the source, make the changes, and continue moving forward. Emile From kent37 at tds.net Mon Aug 4 20:46:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 14:46:20 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <489748EA.1080508@rogers.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> <489748EA.1080508@rogers.com> Message-ID: <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> On Mon, Aug 4, 2008 at 2:22 PM, Patrick <optomatic at rogers.com> wrote: > it seemed to me that Django is well suited for a developer team but is a bit > sketchy when you try to scale it down to a single developer. Why do you say that? Django works fine with a single developer. Kent From kent37 at tds.net Mon Aug 4 20:50:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 14:50:04 -0400 Subject: [Tutor] My experience on web.py In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <1c2a2c590808041150i3f702421s33b24c1382df278d@mail.gmail.com> On Mon, Aug 4, 2008 at 2:04 PM, ammar azif <ceasar102 at yahoo.com> wrote: > I tried to use django but I found that the framework hides > alot of things from me and files are generated by the framework > automaticaly and I felt like I wasnt in control. I'm surprised to hear this. Django generates a few very simple files when you start a project but other than that it is your code. I guess there is a lot that goes on under the hood in the models but I always felt like the major parts of the app were clearly exposed. Anyway I have heard good things about web.py too, you should stick with what works for you. Kent From optomatic at rogers.com Mon Aug 4 20:58:43 2008 From: optomatic at rogers.com (Patrick) Date: Mon, 04 Aug 2008 14:58:43 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> <489748EA.1080508@rogers.com> <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> Message-ID: <48975163.5030008@rogers.com> Oh oh, I did not mean to slag Django! I was basing this on the talk given by Jacob Kaplin-Moss(one of the developers). He gave a great talk but became a bit evasive when he was questioned about Django scaling down to a single developer, specifically when he was questioned about the template views portion. "IT SEEMED" I am not qualified to give advice on Django, sorry if I ticked off anyone! Anyone here using CherryPy? Did anyone consider it and then pass on it? -Patrick Kent Johnson wrote: > On Mon, Aug 4, 2008 at 2:22 PM, Patrick <optomatic at rogers.com> wrote: > > >> it seemed to me that Django is well suited for a developer team but is a bit >> sketchy when you try to scale it down to a single developer. >> > > Why do you say that? Django works fine with a single developer. > > Kent > > From kent37 at tds.net Mon Aug 4 23:22:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Aug 2008 17:22:31 -0400 Subject: [Tutor] My experience on web.py / CherryPy In-Reply-To: <48975163.5030008@rogers.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> <489748EA.1080508@rogers.com> <1c2a2c590808041146q7fd4bb42sa2c92fd006c52158@mail.gmail.com> <48975163.5030008@rogers.com> Message-ID: <1c2a2c590808041422n3f306423uace953af31f3fd3a@mail.gmail.com> On Mon, Aug 4, 2008 at 2:58 PM, Patrick <optomatic at rogers.com> wrote: > Oh oh, I did not mean to slag Django! I didn't take it that way, no worries! > I was basing this on the talk given by Jacob Kaplin-Moss(one of the > developers). He gave a great talk but became a bit evasive when he was > questioned about Django scaling down to a single developer, specifically > when he was questioned about the template views portion. Strange. I can't think of any reason why Django would not be suitable for a single developer. Of course the developer has to understand HTML and probably CSS and JavaScript but that is no different than any other web development tool. Googling finds this: http://www.cmlenz.net/archives/2006/08/the-python-web-framework which seems to refer to the same talk. I am not a fan of the Django template language - I think it is too restrictive - but I don't see how it is harder to use it as a single developer than it would be for a team... Kent From simozack at yahoo.it Tue Aug 5 11:22:15 2008 From: simozack at yahoo.it (simone) Date: Tue, 05 Aug 2008 11:22:15 +0200 Subject: [Tutor] Any Italian speakers? In-Reply-To: <8635291937C04629B8D8AB50677E206E@xp> References: <8635291937C04629B8D8AB50677E206E@xp> Message-ID: <48981BC7.5030508@yahoo.it> Alan Gauld ha scritto: > ------------------- > voglio chiderti solo 1 cosa ... ma secondo te qualle e il miglior > programma X programmare??? > grazie ... > > da Cristian > ----------------- Literally: ------------------- "I want to ask you only one thing... what's in your opinion the best program to program?" from Cristian ------------------- -- Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From nkv at hcoop.net Tue Aug 5 08:05:01 2008 From: nkv at hcoop.net (nkv at hcoop.net) Date: Tue, 5 Aug 2008 02:05:01 -0400 (EDT) Subject: [Tutor] My experience on web.py In-Reply-To: <196711.50013.qm@web56813.mail.re3.yahoo.com> References: <196711.50013.qm@web56813.mail.re3.yahoo.com> Message-ID: <11987.198.182.52.26.1217916301.squirrel@mail.hcoop.net> [..] > share > their thoughts on these > matters,? I've been using TurboGears for a long time now. The documentation is a little patchy (reads more like a bunch of recipes) but the components which form the framework are all separate projects - each individually capable of standing on it's own legs. Also, the TG mailing list is extremely responsive and helpful. It's quick to get an app up and running and while some of the details are hidden, I've found that most of those are the things which I don't want to mess with. It's got a lot of nice components for authentication and things like that which make development quite nice. From ricaraoz at gmail.com Mon Aug 4 16:27:29 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 04 Aug 2008 11:27:29 -0300 Subject: [Tutor] removing whole numbers from text In-Reply-To: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> References: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> Message-ID: <489711D1.8030808@bigfoot.com> Dinesh B Vadhia wrote: > I want to remove whole numbers from text but retain numbers attached to > words. All whole numbers to be removed have a leading and trailing space. > > For example, in "the cow jumped-20 feet high30er than the lazy 20 timing > fox who couldn't keep up the 865 meter race." remove the whole numbers > 20 and 865 but keep the 20 in jumped-20 and the 30 in high30er. > > What is the best to do this using re? > > Dinesh >>> text = "the cow jumped-20 feet high30er than the lazy 20 timing fox who couldn't keep up the 865 meter race." >>> ' '.join(i for i in text.split() if not i.isdigit()) "the cow jumped-20 feet high30er than the lazy timing fox who couldn't keep up the meter race." HTH From monjissvel at googlemail.com Tue Aug 5 13:08:57 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 11:08:57 +0000 Subject: [Tutor] removing whole numbers from text In-Reply-To: <489711D1.8030808@bigfoot.com> References: <BAY109-DS404DF1410C26820D38CD6A37E0@phx.gbl> <489711D1.8030808@bigfoot.com> Message-ID: <e2f191310808050408i4a5869eam91f4f47f48e627ce@mail.gmail.com> [root at serv ~]# python Python 2.5.1 (r251:54863, Nov 23 2007, 16:16:53) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import re >>> >>> a = 'this is a simple 3xampl3 of 2 or 3 numb3rs' # some text >>> b = re.sub('\b[0-9]\b', 'xx', a) # you need to use the r (raw) or else it does work >>> print b this is a simple 3xampl3 of 2 or 3 numb3rs >>> b = re.sub(r'\b[0-9]\b', 'xx', a) #replace with xx >>> print b this is a simple 3xampl3 of xx or xx numb3rs >>> b = re.sub(r'\b[0-9]\b', '', a) #replace with nothing >>> print b this is a simple 3xampl3 of or numb3rs >>> 2008/8/4 Ricardo Ar?oz <ricaraoz at gmail.com> > Dinesh B Vadhia wrote: > >> I want to remove whole numbers from text but retain numbers attached to >> words. All whole numbers to be removed have a leading and trailing space. >> For example, in "the cow jumped-20 feet high30er than the lazy 20 timing >> fox who couldn't keep up the 865 meter race." remove the whole numbers 20 >> and 865 but keep the 20 in jumped-20 and the 30 in high30er. >> What is the best to do this using re? >> Dinesh >> > > >>> text = "the cow jumped-20 feet high30er than the lazy 20 timing fox who > couldn't keep up the 865 meter race." > > >>> ' '.join(i for i in text.split() if not i.isdigit()) > "the cow jumped-20 feet high30er than the lazy timing fox who couldn't keep > up the meter race." > > > HTH > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/92e82f30/attachment.htm> From jmorcombe at westnet.com.au Tue Aug 5 13:01:59 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Tue, 05 Aug 2008 19:01:59 +0800 Subject: [Tutor] regular expressions Message-ID: <48983327.5040804@westnet.com.au> Could someone please give me some help using the "re" module. This works: -------------------------------- import re text = "Jim is a good guy" s2 = re.sub('Jim', 'Fred', text) print s2 and I get "Fred is a good guy" --------------------------------- If I have: text = "Bill Smith is nice" how do I get rid of "Smith" and just have "Bill is nice" I tried s2 = re.sub('Smith', '', text) but it complained. If I have: text = "Jim likes a girl (Susan)" and I want to get rid of "(Susan)", how do I do this. First, the "(" seems to muck things up. Second, how do I just use "re" to delete characters. I tried using "sub", but it doesn't seem to like Jim Morcombe From arsyed at gmail.com Tue Aug 5 13:51:00 2008 From: arsyed at gmail.com (arsyed) Date: Tue, 5 Aug 2008 07:51:00 -0400 Subject: [Tutor] regular expressions In-Reply-To: <48983327.5040804@westnet.com.au> References: <48983327.5040804@westnet.com.au> Message-ID: <9a2cc7a70808050451t28060c84o5dc5d7237f0d6e7f@mail.gmail.com> On Tue, Aug 5, 2008 at 7:01 AM, Jim Morcombe <jmorcombe at westnet.com.au> wrote: > Could someone please give me some help using the "re" module. > > This works: > -------------------------------- > import re > > text = "Jim is a good guy" > > s2 = re.sub('Jim', 'Fred', text) > print s2 > > and I get "Fred is a good guy" > --------------------------------- > If I have: > text = "Bill Smith is nice" > how do I get rid of "Smith" and just have > "Bill is nice" > > I tried > s2 = re.sub('Smith', '', text) > but it complained. > What was the error message? It should work fine: In [25]: text = 'Bill Smith is nice' In [26]: re.sub('Smith', '', text) Out[26]: 'Bill is nice' > If I have: > text = "Jim likes a girl (Susan)" > and I want to get rid of "(Susan)", how do I do this. > You need to escape the parentheses because those are grouping metacharacters in regular expressions: In [27]: text = 'Jim likes a girl (Susan)' In [28]: re.sub('\(Susan\)', '', text) Out[28]: 'Jim likes a girl ' The regex howot document below explains a lot of this stuff: http://www.amk.ca/python/howto/regex/ > First, the "(" seems to muck things up. > Second, how do I just use "re" to delete characters. I tried using "sub", > but it doesn't seem to like > > Jim Morcombe > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From monjissvel at googlemail.com Tue Aug 5 13:57:23 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 11:57:23 +0000 Subject: [Tutor] regular expressions In-Reply-To: <48983327.5040804@westnet.com.au> References: <48983327.5040804@westnet.com.au> Message-ID: <e2f191310808050457s33029eber871e195d3657e0b4@mail.gmail.com> here is what my interpreter gives : >>> >>> >>> text = "Bill Smith is nice" >>> print text Bill Smith is nice >>> re.sub('Smith', '', text) 'Bill is nice' >>> text = "Jim likes a girl (Susan)" >>> print text Jim likes a girl (Susan) >>> KeyboardInterrupt >>> re.sub('(Susan)', '', text) 'Jim likes a girl ()' >>> re.sub(r'(Susan)', '', text) 'Jim likes a girl ()' >>> re.sub(r'\(Susan\)', '', text) 'Jim likes a girl ' >>> >>> re.sub('a', 'aa', 'I am a girl') 'I aam aa girl' >>> so your code seems to be working you just maybe don't know about the 'r' which mean raw & which tells python to take the special characters as they are without interpreting them. some special characters are : \n (new line), \b (space), \t (tab); \r (cariage return on windows). 2008/8/5 Jim Morcombe <jmorcombe at westnet.com.au> > Could someone please give me some help using the "re" module. > > This works: > -------------------------------- > import re > > text = "Jim is a good guy" > > s2 = re.sub('Jim', 'Fred', text) > print s2 > > and I get "Fred is a good guy" > --------------------------------- > If I have: > text = "Bill Smith is nice" > how do I get rid of "Smith" and just have > "Bill is nice" > > I tried > s2 = re.sub('Smith', '', text) > but it complained. > > If I have: > text = "Jim likes a girl (Susan)" > and I want to get rid of "(Susan)", how do I do this. > > First, the "(" seems to muck things up. > Second, how do I just use "re" to delete characters. I tried using "sub", > but it doesn't seem to like > > Jim Morcombe > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/e985f08d/attachment.htm> From kent37 at tds.net Tue Aug 5 14:41:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 5 Aug 2008 08:41:41 -0400 Subject: [Tutor] regular expressions In-Reply-To: <48983327.5040804@westnet.com.au> References: <48983327.5040804@westnet.com.au> Message-ID: <1c2a2c590808050541s5daa40den4d5c9f537d3c8144@mail.gmail.com> On Tue, Aug 5, 2008 at 7:01 AM, Jim Morcombe <jmorcombe at westnet.com.au> wrote: > Could someone please give me some help using the "re" module. > If I have: > text = "Bill Smith is nice" > how do I get rid of "Smith" and just have > "Bill is nice" > > I tried > s2 = re.sub('Smith', '', text) > but it complained. Please show the specific error message you get; "it complained" is too vague. > > If I have: > text = "Jim likes a girl (Susan)" > and I want to get rid of "(Susan)", how do I do this. > > First, the "(" seems to muck things up. > Second, how do I just use "re" to delete characters. I tried using "sub", > but it doesn't seem to like Again, this is too vague. Show us exactly what you tried and what result you got. BTW you don't need the re module to replace fixed strings with new strings, you can use the replace() method of the string: In [1]: text = "Bill Smith is nice" In [5]: text.replace('Smith', '') Out[5]: 'Bill is nice' Kent From bryan.fodness at gmail.com Tue Aug 5 17:08:57 2008 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Tue, 5 Aug 2008 11:08:57 -0400 Subject: [Tutor] iterating data and populating a dictionary Message-ID: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> i am filling a dictionary with a dictionary and my values for isegment[field] are identical. i can't see where i am overwriting the previous field values. my data looks like Field = aa1 Index = 0.0 Value = 0.0 ... ... Field = aa2 Index = 0.01 Value = 0.5 ... i would like to have something like, {1: {'Value': 0.0, ...}, 2: {'Value': 0.01, ...}} for line in file(data_file): the_line = line.split() if the_line: if the_line[0] == 'Field': field += 1 elif the_line[0] == 'Index': index = float(the_line[-1]) dif_index = index - start_index iindex[field] = dif_index start_index = index elif the_line[0] == 'Value': segment[the_line[1]] = float(the_line[-1])*(ax/40) isegment[field] = segment -- "The game of science can accurately be described as a never-ending insult to human intelligence." - Jo?o Magueijo -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/3f4b7c28/attachment.htm> From monjissvel at googlemail.com Tue Aug 5 17:37:34 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 15:37:34 +0000 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> References: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> Message-ID: <e2f191310808050837j596d237r8c7e055c30cb5f35@mail.gmail.com> maybe this can help MainDictionary = {} N = 0 for line in open('data_file', 'r'): if line: N += 1 a, b = line.split(" = ") # "=" is in between spaces whish gives you only two variables. if a == 'Field': MainDictionary[N] == {} elif a == 'Index': MainDictionary[N]['Value'] = {b} 2008/8/5 Bryan Fodness <bryan.fodness at gmail.com> > i am filling a dictionary with a dictionary and my values for > isegment[field] are identical. i can't see where i am overwriting the > previous field values. > > my data looks like > > Field = aa1 > Index = 0.0 > Value = 0.0 > ... > ... > Field = aa2 > Index = 0.01 > Value = 0.5 > ... > > > i would like to have something like, {1: {'Value': 0.0, ...}, 2: {'Value': > 0.01, ...}} > > for line in file(data_file): > the_line = line.split() > if the_line: > if the_line[0] == 'Field': > field += 1 > elif the_line[0] == 'Index': > index = float(the_line[-1]) > dif_index = index - start_index > iindex[field] = dif_index > start_index = index > elif the_line[0] == 'Value': > segment[the_line[1]] = float(the_line[-1])*(ax/40) > isegment[field] = segment > > > -- > "The game of science can accurately be described as a never-ending insult > to human intelligence." - Jo?o Magueijo > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/f4308401/attachment.htm> From monjissvel at googlemail.com Tue Aug 5 17:43:41 2008 From: monjissvel at googlemail.com (Monika Jisswel) Date: Tue, 5 Aug 2008 15:43:41 +0000 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: <e2f191310808050837j596d237r8c7e055c30cb5f35@mail.gmail.com> References: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> <e2f191310808050837j596d237r8c7e055c30cb5f35@mail.gmail.com> Message-ID: <e2f191310808050843v48784ceav10137bf66f7242b3@mail.gmail.com> oops i forgot to count lines, MainDictionary = {} N = 0 M = 0 for line in open('data_file', 'r'): if line: if M < 3: N += 1 M += 1 a, b = line.split(" = ") # "=" is in between spaces whish gives you only two variables. if a == 'Field': MainDictionary[N] == {} elif a == 'Index': MainDictionary[N]['Value'] = {b} else: a, b = line.split(" = ") # "=" is in between spaces whish gives you only two variables. if a == 'Field': MainDictionary[N] == {} elif a == 'Index': MainDictionary[N]['Value'] = {b} M = 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/94ba6c13/attachment.htm> From federo at email.si Tue Aug 5 13:22:35 2008 From: federo at email.si (Federo) Date: Tue, 05 Aug 2008 13:22:35 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> Message-ID: <20080805112237.020538F19C@www1.email.si> I have tried but I recived error. Look attached files: FormManagementCode (my code) and FormManagement_Note (headers information). There must be some additional trick to fully master form management .. Fake account is now active. URL: https://investor.firstrade.com/firstrade/login.do On screen: We are enetring Symbole field at the top right User: janezfedero Pass: kmet500 (I left login credentials also in the attached code) Cheers, Fedo On Mon, 4 Aug 2008 at 16:08:33, Kent Johnson wrote: > On Mon, Aug 4, 2008 at 8:05 AM, Federo <federo at email.si> wrote: > > Kent THANKS! It works great also on real account .. > > > > Two important Sub-QUESTIONS: > > > > 1.) Look attached word file. It describes form fields I would like to fill > in > > and read server resoult.. > > You just have to mimic what the browser does. Use a Firefox plugin > that shows you what is being submitted; TamperData is one. Then set > the same fields in your code. > > > 2.) Could you do the same login logic also with MECHANIZE plagin. There > are > > some very usefull function in this plagin I might use. However I have > > No, I'm not familiar with mechanize. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet500', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() # print(data) params = dict(username='janezfedero', password='kmet500', destination='', contentProvider='pinnacor', quoteSymbol='XSNX', optionChain='XSNX', countryCode='US', optionRange='NTM', tickerSymbol='XSNX', contentType='stockquote', quote.x='submitted') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do', params) data = f.read() f.close() print(data) -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_Note.rtf Type: application/msword Size: 2945 bytes Desc: FormManagement_Note.rtf URL: <http://mail.python.org/pipermail/tutor/attachments/20080805/f320e631/attachment.wiz> From alan.gauld at btinternet.com Tue Aug 5 18:51:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Aug 2008 17:51:02 +0100 Subject: [Tutor] iterating data and populating a dictionary References: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> Message-ID: <g7a0dn$q9d$1@ger.gmane.org> "Bryan Fodness" <bryan.fodness at gmail.com> wrote > i am filling a dictionary with a dictionary and my values for > isegment[field] are identical. i can't see where i am overwriting > the > previous field values. Show us the full error text do not just summarize. > i would like to have something like, {1: {'Value': 0.0, ...}, 2: > {'Value': Describe the output you expected and what you got (if anything) > for line in file(data_file): > the_line = line.split() > if the_line: > if the_line[0] == 'Field': > field += 1 > elif the_line[0] == 'Index': > index = float(the_line[-1]) > dif_index = index - start_index > iindex[field] = dif_index Here index is assigned to a floating point number. Then it is indexed. Floats don't have indexes... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Aug 5 22:42:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Aug 2008 21:42:59 +0100 Subject: [Tutor] iterating data and populating a dictionary References: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> <g7a0dn$q9d$1@ger.gmane.org> Message-ID: <g7ae0l$ce8$1@ger.gmane.org> "Alan Gauld" <alan.gauld at btinternet.com> wrote >> index = float(the_line[-1]) >> dif_index = index - start_index >> iindex[field] = dif_index > > Here index is assigned to a floating point number. > Then it is indexed. Floats don't have indexes... Just noticed the indexed variable has a double i so not the same. Might be better to pick a more descriptive name though! :-) Alan G. From rdmoores at gmail.com Wed Aug 6 00:49:14 2008 From: rdmoores at gmail.com (Dick Moores) Date: Tue, 5 Aug 2008 15:49:14 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() Message-ID: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> For a while now I've had trouble with end_fill(). Sometimes I can use it to fill a figure such as a square, triangle or rectangle, but sometimes not. Here's a barebones script using end_fill(). As you can see, it draws a square twice, but fails to fill it. Pleas show me how to use it correctly in tandem with begin_fill(). The Turtle doc is at <http://docs.python.org/lib/module-turtle.html> ============================ from turtle import * import time setup(width=1000, height=700, startx=0, starty=0) for n in range(2): begin_fill() color_name = 'red' x, y = 50, 50 color(color_name) print color_name up() goto(x, y) down() goto(x, -y) goto(-x, -y) goto(-x, y) goto(x, y) end_fill() print "end_fill()" time.sleep(1) clear() ===================================== Thanks, Dick Moores From carroll at tjc.com Wed Aug 6 03:29:37 2008 From: carroll at tjc.com (Terry Carroll) Date: Tue, 5 Aug 2008 18:29:37 -0700 (PDT) Subject: [Tutor] Decimals 'not equal to themselves' (e.g. 0.2 equals 0.200000001) In-Reply-To: <4895BAD9.5010004@icedcerulean.com> Message-ID: <Pine.LNX.4.44.0808051803510.6112-100000@violet.rahul.net> On Sun, 3 Aug 2008, CNiall wrote: > >>> 0.2 > 0.20000000000000001 > >>> 0.33 > 0.33000000000000002 > > As you can see, the last two decimals are very slightly inaccurate. > However, it appears that when n in 1/n is a power of two, the decimal > does not get 'thrown off'. How might I make Python recognise 0.2 as 0.2 > and not 0.20000000000000001? It's not a Python thing, it's a computer thing. Thsi would be present regardless of what computer language you're using. An oversimplificationis that computers use binary, i.e., base-2. The only non-1 factor of 2 is 2 itself, and computers can only give you an exact representation of a fraction whose denominator only has factors of 2. So these are exact representations: >>> .5 0.5 >>> .5 # 1/2 0.5 >>> .25 # 1/4 0.25 >>> .125 # 1/8 0.125 >>> .875 # 7/8 0.875 But suppose you want 1/10. Well, 10 is factored into 2 and 5, and that pesky 5 makes it impossible for a computer to store exactly; same with 1/5: >>> .1 # 1/10 0.10000000000000001 >>> .2 # 1/5 0.20000000000000001 Do you remember when you learned decimal fractions in garde school, and realized you couldn't represent, for example, 1/3 or 1/7 exactly? You had to content yourself with 0.3333333.... or 0.14285714285714285... with digits repeating forever? That's the equivalent problem in our usual base-10: we can't exactly represent any fraction unless the denominator factors only into 2s and 5s (which are the factors of 10). So representing 1/2, 1/4, 1/20 all are no problem in decimal; but 1/3 and 1/21 can't be exactly represented. A corallary of this, by the way, is that, because there are so many fractions that can't be exactly represented in binary notation, you should never compare floating point numbers looking for equality. It just won't work. Consider the following code: >>> x = 0.0 >>> while x != 1.0: ... print x ... x = x + 1.0/7.0 You might expect this to look through 0.0, 0.142...., 0.285..., 0.428.... up to 10., and then stop. But it won't. because it never quite equals 1.0. It goes right up to a number near 1.0, that might display as 1.0, but is not really 1.0, and blasts on through to 1.142... etc, in an endless loop. So when comparing floating point numbers you should either use a comparison like >= (if using it as a limit) or a construct like if abs(x-y)<.00001: to see if they're close enough to equal to keep you happy. From alan.gauld at btinternet.com Wed Aug 6 11:41:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Aug 2008 10:41:47 +0100 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> Message-ID: <g7brkt$tov$1@ger.gmane.org> "Dick Moores" <rdmoores at gmail.com> wrote > Here's a barebones script using end_fill(). As you can see, it draws > a > square twice, but fails to fill it. Pleas show me how to use it > correctly in tandem with begin_fill(). > > The Turtle doc is at <http://docs.python.org/lib/module-turtle.html> How odd. I can't get it to work either but it does in the turtle demo. Even cut n pasting the demo code into a function didn't work for me. I'm curious if anyone else gets this one working? I'm on XP, Python 2.5 BTW Alan G. From lie.1296 at gmail.com Wed Aug 6 12:22:22 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 06 Aug 2008 17:22:22 +0700 Subject: [Tutor] Tutor Digest, Vol 54, Issue 16 In-Reply-To: <mailman.11900.1217955082.920.tutor@python.org> References: <mailman.11900.1217955082.920.tutor@python.org> Message-ID: <1218018142.6394.13.camel@lieryan-laptop> > Message: 1 > Date: Tue, 5 Aug 2008 11:08:57 -0400 > From: "Bryan Fodness" <bryan.fodness at gmail.com> > Subject: [Tutor] iterating data and populating a dictionary > To: "tutorpythonmailinglist Python" <tutor at python.org> > Message-ID: > <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > i am filling a dictionary with a dictionary and my values for > isegment[field] are identical. i can't see where i am overwriting the > previous field values. > > my data looks like > > Field = aa1 > Index = 0.0 > Value = 0.0 > ... > ... > Field = aa2 > Index = 0.01 > Value = 0.5 > ... > > > i would like to have something like, {1: {'Value': 0.0, ...}, 2: > {'Value':0.01, ...}} Why don't you use a list of dictionaries instead of dictionaries of dictionaries? > > for line in file(data_file): > the_line = line.split() It's better to use: line.split('=', 1) then you should consider stripping its values, especially the one to be used as the key to the dictionary. > if the_line: > if the_line[0] == 'Field': > field += 1 if this code snippet is the only code in your program, field would cause NameError. However, I assume you have declared field somewhere outside this line, and field is a local variable. If that is the case, remember that local variable is deleted when it is out of scope. This might be the reason why Fields got overwritten. > elif the_line[0] == 'Index': > index = float(the_line[-1]) If you use .split('=', 1), you can be sure that the value of the dictionary is on the_line[1] and the key of the dictionary is on the_line[0] (assuming = is not a legal character for key name) > dif_index = index - start_index > iindex[field] = dif_index > start_index = index > elif the_line[0] == 'Value': > segment[the_line[1]] = float(the_line[-1])*(ax/40) > isegment[field] = segment This particular snippet isn't enough to localize the source of your problem. From kent37 at tds.net Wed Aug 6 13:50:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 6 Aug 2008 07:50:42 -0400 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() In-Reply-To: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> Message-ID: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores <rdmoores at gmail.com> wrote: > For a while now I've had trouble with end_fill(). Sometimes I can use > it to fill a figure such as a square, triangle or rectangle, but > sometimes not. > > Here's a barebones script using end_fill(). As you can see, it draws a > square twice, but fails to fill it. Pleas show me how to use it > correctly in tandem with begin_fill(). Here is a version that does fill: from turtle import * import time setup(width=1000, height=700, startx=0, starty=0) for n in range(2): color_name = 'red' x, y = 50, 50 color(color_name) print color_name up() goto(x, y) down() begin_fill() goto(x, -y) goto(-x, -y) goto(-x, y) end_fill() print "end_fill()" goto(x, y) time.sleep(1) clear() I have no idea why this one works and yours doesn't. Your program is very similar to the filled square in turtle.demo() which does work. The filling is implemented by drawing a polygon on a Tkinter Canvas; is there something strange about polygons? Kent From rdmoores at gmail.com Wed Aug 6 15:33:51 2008 From: rdmoores at gmail.com (Dick Moores) Date: Wed, 6 Aug 2008 06:33:51 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() In-Reply-To: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> Message-ID: <d71c7ed60808060633i6b3ff25fi527b35b644410398@mail.gmail.com> On Wed, Aug 6, 2008 at 4:50 AM, Kent Johnson <kent37 at tds.net> wrote: > On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores <rdmoores at gmail.com> wrote: >> For a while now I've had trouble with end_fill(). Sometimes I can use >> it to fill a figure such as a square, triangle or rectangle, but >> sometimes not. >> >> Here's a barebones script using end_fill(). As you can see, it draws a >> square twice, but fails to fill it. Pleas show me how to use it >> correctly in tandem with begin_fill(). > > Here is a version that does fill: > from turtle import * > import time > > setup(width=1000, height=700, startx=0, starty=0) > for n in range(2): > color_name = 'red' > x, y = 50, 50 > color(color_name) > print color_name > up() > goto(x, y) > down() > begin_fill() > goto(x, -y) > goto(-x, -y) > goto(-x, y) > end_fill() > print "end_fill()" > goto(x, y) > time.sleep(1) > clear() > > I have no idea why this one works and yours doesn't. Your program is > very similar to the filled square in turtle.demo() which does work. Well, Kent, it seems you have found the right places for begin_fill() and end_fill(). The 450-line script I was writing now works perfectly at last, in what is now version 15. Thanks very much. And my thanks also to Alan. Dick From norman at khine.net Wed Aug 6 21:59:40 2008 From: norman at khine.net (Norman Khine) Date: Wed, 6 Aug 2008 21:59:40 +0200 Subject: [Tutor] Merging dictionaries Message-ID: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Hello, I am trying to figure out the best way to add results from a poll module that I have working, but am a bit stuck and can't see on how to add the total responses submitted by the user. So far I have an output which puts in a list all the user's responses, such as responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]} .... ] Is this an efficient way to do this, say for example I have 1000's of responses? What is the best way to append value items of dictionaries, such that: responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] is transformmed into: answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} I have tried this: Type "help", "copyright", "credits" or "license" for more information. >>> ret = {} >>> myvalues = [] >>> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] >>> for response in responses: mykeys = [] for answer in response.items(): mykeys.append(answer[0]) for key in mykeys: if not ret.has_key(key): ret[key] = [] else: ret[key].append(answer[1]) >>> print ret {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} But is not correct ;'( And finally, what is the simplest way to count the nummber of occurances, so that: answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} returns totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]} I tried this: ret = {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} storage = {} for code in ret: for answer, x in questions.items(): for x in x: if not storage.has_key(x): storage[x] = {'count': 1} else: storage[x]['count'] += 1 print storage But this did not work either. Cheers Norman From kent37 at tds.net Wed Aug 6 23:01:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 6 Aug 2008 17:01:50 -0400 Subject: [Tutor] Merging dictionaries In-Reply-To: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Message-ID: <1c2a2c590808061401l30c1adf2r98fc2c6bf73ff8a7@mail.gmail.com> On Wed, Aug 6, 2008 at 3:59 PM, Norman Khine <norman at khine.net> wrote: > So far I have an output which puts in a list all the user's responses, such as > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]} .... ] > > Is this an efficient way to do this, say for example I have 1000's of responses? It's OK, though if you just want the counts, as you create below, you might want to accumulate them directly. > What is the best way to append value items of dictionaries, such that: > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] > > is transformmed into: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} collections.defaultdict is very useful when you want to accumulate dictionary values of any kind. When you look up a key in a defaultdict, if the key is not found, a default value is supplied. Thus you don't have to distinguish the first appearance of a key from subsequent appearances. The other thing you need is list.extend(), which adds the elements of one list to the end of another. In [1]: from collections import defaultdict In [2]: responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] In [3]: answered = defaultdict(list) In [5]: for response in responses: ...: for q, a in response.items(): ...: answered[q].extend(a) In [6]: answered Out[6]: defaultdict(<type 'list'>, {'a1': [1, 0], 'a2': [1, 2, 3, 0, 1, 3]}) > And finally, what is the simplest way to count the nummber of occurances, so > that: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} > > returns > > totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]} Again, defaultdict to the rescue: In [8]: totals = {} In [10]: for q, answers in answered.items(): ....: counts = totals[q] = defaultdict(int) ....: for a in answers: ....: counts[a] += 1 In [11]: totals Out[11]: {'a1': defaultdict(<type 'int'>, {0: 1, 1: 1}), 'a2': defaultdict(<type 'int'>, {0: 1, 1: 2, 2: 1, 3: 2})} Kent From alan.gauld at btinternet.com Thu Aug 7 01:15:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Aug 2008 00:15:46 +0100 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com><1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <d71c7ed60808060633i6b3ff25fi527b35b644410398@mail.gmail.com> Message-ID: <g7dbb4$52f$1@ger.gmane.org> "Dick Moores" <rdmoores at gmail.com> wrote > Well, Kent, it seems you have found the right places for > begin_fill() > and end_fill(). Yes, quite bizarrely the fill needs an open shape to fill. If you close the figure and then end_fill it doesn't work. How counter intuitive is that! Oh well, one to remember for future use. Alan G. From gregor.lingl at aon.at Thu Aug 7 02:09:15 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Thu, 07 Aug 2008 02:09:15 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py In-Reply-To: <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> Message-ID: <489A3D2B.1020603@aon.at> Kent Johnson schrieb: > On Tue, Aug 5, 2008 at 6:49 PM, Dick Moores <rdmoores at gmail.com> wrote: > >> For a while now I've had trouble with end_fill(). Sometimes I can use >> it to fill a figure such as a square, triangle or rectangle, but >> sometimes not. >> >> Here's a barebones script using end_fill(). As you can see, it draws a >> square twice, but fails to fill it. Pleas show me how to use it >> correctly in tandem with begin_fill(). >> > > Hi all, Kent's version below repairs the problem more or less accidentally and moreover not completely: (1) the first square is not filled properly; instead a filled pentagon appears after the first traversal of the loop. (2) the filling takes place due to the goto() call after the end_fill() call and before the clear() call. This is due to a bug in turtle.py - interestingly after so many years of use and improvement of turtle.py there still appear new bugs from time to time. The bug consists in a missing update of the Canvas in the fill() function You can repair it by inserting a line at line#309 in turtle.py in the fill method as follows: if self._filling: path = tuple(self._path) smooth = self._filling < 0 if len(path) > 2: item = self._canvas._create('polygon', path, {'fill': self._color, 'smooth': smooth}) self._items.append(item) self._canvas.update() # <=== bug-fix self._path = [] Now for the good news: (1) If you have done this, not only Dick's program works as intended, but you may also write the square_filling program in a cleaner way, for instance like this: from turtle import * import time setup(width=1000, height=700, startx=0, starty=0) color_name = 'red' x, y = 50, 50 color(color_name) print color_name up() goto(x, y) down() for n in range(2): begin_fill() goto(x, -y) goto(-x, -y) goto(-x, y) goto(x, y) end_fill() print "end_fill()" time.sleep(1) clear() (2) Python 2.6 will have a new turtle module - formerly known to some as xturtle.py - which has much more capabilities and which at least doesn't show this bug. Presumably there will appear others, especially in the beginning of it's use. It is contained in Python2.6 beta2, it runs also under Python2.5 and it should be (nearly?) 100%-compatible with the old turtle module. Its documentation can be found here: http://docs.python.org/dev/library/turtle.html#module-turtle It would be really very helpful, if those of you who use to use turtle graphcis would work with this new module in order to reveal as many bugs as possible before the final release of Python 2.6 scheduled for early october 2008. Of course I'd assist if questions or problems would arise. Regards Gregor > Here is a version that does fill: > from turtle import * > import time > > setup(width=1000, height=700, startx=0, starty=0) > for n in range(2): > color_name = 'red' > x, y = 50, 50 > color(color_name) > print color_name > up() > goto(x, y) > down() > begin_fill() > goto(x, -y) > goto(-x, -y) > goto(-x, y) > end_fill() > print "end_fill()" > goto(x, y) > time.sleep(1) > clear() > > I have no idea why this one works and yours doesn't. Your program is > very similar to the filled square in turtle.demo() which does work. > > The filling is implemented by drawing a polygon on a Tkinter Canvas; > is there something strange about polygons? > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From benoit.thiell at cern.ch Thu Aug 7 07:21:36 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Thu, 7 Aug 2008 01:21:36 -0400 Subject: [Tutor] Merging dictionaries In-Reply-To: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Message-ID: <alpine.DEB.1.10.0808070114550.15872@pcuds30> Dear Norman, I would propose: ret = {} myvalues = [] responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, 3]}] for response in responses: for answer in response.items() ret.setdefault(response[0], []).append(response[1]) Regards, Benoit Thiell. From technorapture at gmail.com Thu Aug 7 07:42:58 2008 From: technorapture at gmail.com (Shrutarshi Basu) Date: Thu, 7 Aug 2008 01:42:58 -0400 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: <g7ae0l$ce8$1@ger.gmane.org> References: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> <g7a0dn$q9d$1@ger.gmane.org> <g7ae0l$ce8$1@ger.gmane.org> Message-ID: <376fbdcf0808062242p6066f18bi9d8dbd3b1aedb638@mail.gmail.com> If you're just going to be using numbers as dictionary keys, it might be simpler just to use a list structure. Dictionaries don't preserve order, so you'd need to write extra code if you ever need to iterate over it in order. Since your code increments field everytime it gets a new record you can just use it as a list index and things should be fine. Of course you might have your own reasons for using a dict, so it's up to you. -- The ByteBaker : http://www.bytebaker.com From cspears2002 at yahoo.com Thu Aug 7 08:01:02 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 6 Aug 2008 23:01:02 -0700 (PDT) Subject: [Tutor] date formatter Message-ID: <440786.53671.qm@web51601.mail.re2.yahoo.com> Hey, I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far: #!/usr/bin/python import time class date_format(object): def __init__(self, month, day, year): month_dict = {("jan","january") : 1, ("feb","february") :2, ("mar", "march") : 3, ("apr", "april") : 4, ("may") : 5, ("jun", "june") : 6, ("jul", "july") : 7, ("aug", "august") : 8, ("sep", "september") : 9, ("oct", "october"): 10, ("nov", "november"): 11, ("dec", "december"): 12 } try: month = int(month) except ValueError: for eachKey in month_dict.keys(): if month.lower() in eachKey: month = month_dict[eachKey] else: month = "" if month=="" or day=="" or year=="": self.date = time.localtime() else: self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1) def display(self, format_indicator = None): if format_indicator == 'MDY': print time.strftime("%m/%d/%y",self.date) elif format_indicator == 'MDYY': print time.strftime("%m/%d/%Y",self.date) elif format_indicator == 'DMY': print time.strftime("%d/%m/%y",self.date) elif format_indicator == 'DMYY': print time.strftime("%d/%m/%Y",self.date) elif format_indicator == 'MODYY': print time.strftime("%b %d, %Y",self.date) else: print time.strftime("%a %b %d %Y",self.date) if __name__ == "__main__": print "Welcome to the Date Formatter!" month = raw_input("Please enter a month: ") day = raw_input("Please enter a day: ") year = raw_input("Please enter a year: ") date_obj = date_format(month, day, year) format_indicator = raw_input("Enter a format indicator: ") date_obj.display(format_indicator.upper()) I am having trouble dealing with the case where the user actually types in a month's name instead of the number: io at io-station-1 ./chap13 180> python date_format_v01.py Welcome to the Date Formatter! Please enter a month (as a number): Oct Please enter a day: 31 Please enter a year: 1976 Traceback (most recent call last): File "date_format_v01.py", line 53, in ? date_obj = date_format(month, day, year) File "date_format_v01.py", line 24, in __init__ if month.lower() in eachKey: AttributeError: 'int' object has no attribute 'lower' Any suggestions? -Chris From timothy.grant at gmail.com Thu Aug 7 08:05:33 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 6 Aug 2008 23:05:33 -0700 Subject: [Tutor] date formatter In-Reply-To: <440786.53671.qm@web51601.mail.re2.yahoo.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> Message-ID: <e775286d0808062305v4bc87b12rfa26996df68266dc@mail.gmail.com> On Wed, Aug 6, 2008 at 11:01 PM, Christopher Spears <cspears2002 at yahoo.com> wrote: > Hey, > > I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far: > > #!/usr/bin/python > > import time > > class date_format(object): > def __init__(self, month, day, year): > month_dict = {("jan","january") : 1, > ("feb","february") :2, > ("mar", "march") : 3, > ("apr", "april") : 4, > ("may") : 5, > ("jun", "june") : 6, > ("jul", "july") : 7, > ("aug", "august") : 8, > ("sep", "september") : 9, > ("oct", "october"): 10, > ("nov", "november"): 11, > ("dec", "december"): 12 > } > try: > month = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month = month_dict[eachKey] > else: > month = "" > if month=="" or day=="" or year=="": > self.date = time.localtime() > else: > self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1) > > def display(self, format_indicator = None): > if format_indicator == 'MDY': > print time.strftime("%m/%d/%y",self.date) > elif format_indicator == 'MDYY': > print time.strftime("%m/%d/%Y",self.date) > elif format_indicator == 'DMY': > print time.strftime("%d/%m/%y",self.date) > elif format_indicator == 'DMYY': > print time.strftime("%d/%m/%Y",self.date) > elif format_indicator == 'MODYY': > print time.strftime("%b %d, %Y",self.date) > else: > print time.strftime("%a %b %d %Y",self.date) > > > if __name__ == "__main__": > print "Welcome to the Date Formatter!" > month = raw_input("Please enter a month: ") > day = raw_input("Please enter a day: ") > year = raw_input("Please enter a year: ") > date_obj = date_format(month, day, year) > format_indicator = raw_input("Enter a format indicator: ") > date_obj.display(format_indicator.upper()) > > I am having trouble dealing with the case where the user actually types in a month's name instead of the number: > io at io-station-1 ./chap13 180> python date_format_v01.py > > Welcome to the Date Formatter! > Please enter a month (as a number): Oct > Please enter a day: 31 > Please enter a year: 1976 > Traceback (most recent call last): > File "date_format_v01.py", line 53, in ? > date_obj = date_format(month, day, year) > File "date_format_v01.py", line 24, in __init__ > if month.lower() in eachKey: > AttributeError: 'int' object has no attribute 'lower' > > Any suggestions? > -Chris wrap the call to month.lower() in a try/except block. try: if month.lower() ..... except AttributeError: process this as a string instead of a number.... -- Stand Fast, tjg. [Timothy Grant] From wescpy at gmail.com Thu Aug 7 08:39:26 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 6 Aug 2008 23:39:26 -0700 Subject: [Tutor] date formatter In-Reply-To: <440786.53671.qm@web51601.mail.re2.yahoo.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> Message-ID: <78b3a9580808062339s464cfbdep40e720179ee774e9@mail.gmail.com> > try: > month = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month = month_dict[eachKey] > else: > month = "" > : > I am having trouble dealing with the case where the user actually types in a month's name instead of the number: > io at io-station-1 ./chap13 180> python date_format_v01.py > : > if month.lower() in eachKey: > AttributeError: 'int' object has no attribute 'lower' > > Any suggestions? chris, good 1st attempt. all the problems are in the code snippet above. you only have a few flaws in your program preventing it from working: a. you "wipe out" the originally entered month (by continually reassigning the month var) b. you don't break out of the inner for-loop when u find a match and end up wiping out the correct match c. the cause of the exception: the entry for May is a string and not a 1-item tuple. you need a trailing comma "," after "may" to make it a tuple. the reason why the error is triggered is because you set a blank to month for every non-match. so when it gets to may, it makes this comparison: >>> "" in "may" True because of this, it sets... month = month_dict["may"] # so month == 5 so in the next loop iteration, your're trying to do... 5.lower() in eachKey which of course, fails. fix these problems, and you have a working solution! best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Aug 7 08:53:24 2008 From: wescpy at gmail.com (wesley chun) Date: Wed, 6 Aug 2008 23:53:24 -0700 Subject: [Tutor] Merging dictionaries In-Reply-To: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> Message-ID: <78b3a9580808062353w1f3a390sa01a0de809a595e6@mail.gmail.com> hmmm, somewhat off-topic, i was partially confused by the Subject line. i thought this post was about merging *dictionaries* and not merging the *contents of multiple dictionaries' values*. for those who are interested in the former, you use the update() method and here is an example: >>> d1 = dict(zip(range(3), range(3))) >>> d1 {0: 0, 1: 1, 2: 2} >>> d2 = dict(zip(range(2,5), [i*2 for i in range(2, 5)])) >>> d2 {2: 4, 3: 6, 4: 8} >>> d1.update(d2) >>> d1 {0: 0, 1: 1, 2: 4, 3: 6, 4: 8} notice that the update will replace any existing key with the corresponding value of the argument dict. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bgailer at gmail.com Thu Aug 7 13:19:58 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 07 Aug 2008 04:19:58 -0700 Subject: [Tutor] date formatter In-Reply-To: <440786.53671.qm@web51601.mail.re2.yahoo.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> Message-ID: <489ADA5E.1080607@gmail.com> Christopher Spears wrote: > Hey, > > I'm working on a problem out of Core Python Programming (2nd Edition). Basically, I'm creating a class that formats dates. Here is what I have so far: > Consider reformatting the month_dict so each name and abbreviation is a key. Then you can just look up the potential key rather than looping thru all the keys. That is what dictionaries are for!: month_dict = {"jan" : 1, "january" : 1, "feb" : 2, "february" :2, etc ...} ... except ValueError: if month.lower() in month_dict: month = month_dict[month.lower()] else: month = "" The dict function is also handy here: month_dict = dict( jan = 1, january = 1, feb = 2, february = 2, etc ...) Consider using another dictionary for the formats: format_dict = dict( MDY = "%m/%d/%y", MDYY = "%m/%d/%Y", DMY = "%d/%m/%y", DMYY = "%d/%m/%Y", MODYY = "%b %d, %Y",) > #!/usr/bin/python > > import time > > class date_format(object): > def __init__(self, month, day, year): > month_dict = {("jan","january") : 1, > ("feb","february") :2, > ("mar", "march") : 3, > ("apr", "april") : 4, > ("may") : 5, > ("jun", "june") : 6, > ("jul", "july") : 7, > ("aug", "august") : 8, > ("sep", "september") : 9, > ("oct", "october"): 10, > ("nov", "november"): 11, > ("dec", "december"): 12 > } > try: > month = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month = month_dict[eachKey] > else: > month = "" > if month=="" or day=="" or year=="": > self.date = time.localtime() > else: > self.date = (int(year), month, int(day), 0, 0, 0, 0, 1, -1) > > def display(self, format_indicator = None): > if format_indicator == 'MDY': > print time.strftime("%m/%d/%y",self.date) > elif format_indicator == 'MDYY': > print time.strftime("%m/%d/%Y",self.date) > elif format_indicator == 'DMY': > print time.strftime("%d/%m/%y",self.date) > elif format_indicator == 'DMYY': > print time.strftime("%d/%m/%Y",self.date) > elif format_indicator == 'MODYY': > print time.strftime("%b %d, %Y",self.date) > else: > print time.strftime("%a %b %d %Y",self.date) > > > if __name__ == "__main__": > print "Welcome to the Date Formatter!" > month = raw_input("Please enter a month: ") > day = raw_input("Please enter a day: ") > year = raw_input("Please enter a year: ") > date_obj = date_format(month, day, year) > format_indicator = raw_input("Enter a format indicator: ") > date_obj.display(format_indicator.upper()) > > I am having trouble dealing with the case where the user actually types in a month's name instead of the number: > io at io-station-1 ./chap13 180> python date_format_v01.py > > Welcome to the Date Formatter! > Please enter a month (as a number): Oct > Please enter a day: 31 > Please enter a year: 1976 > Traceback (most recent call last): > File "date_format_v01.py", line 53, in ? > date_obj = date_format(month, day, year) > File "date_format_v01.py", line 24, in __init__ > if month.lower() in eachKey: > AttributeError: 'int' object has no attribute 'lower' > > Any suggestions? > -Chris > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From benoit.thiell at cern.ch Thu Aug 7 13:39:55 2008 From: benoit.thiell at cern.ch (Benoit Thiell) Date: Thu, 7 Aug 2008 13:39:55 +0200 Subject: [Tutor] date formatter In-Reply-To: <489ADA5E.1080607@gmail.com> References: <440786.53671.qm@web51601.mail.re2.yahoo.com> <489ADA5E.1080607@gmail.com> Message-ID: <alpine.DEB.1.10.0808071336300.3743@pcuds30> On Thu, 7 Aug 2008, bob gailer wrote: > Christopher Spears wrote: >> Hey, >> >> I'm working on a problem out of Core Python Programming (2nd Edition). >> Basically, I'm creating a class that formats dates. Here is what I have so >> far: >> > > Consider reformatting the month_dict so each name and abbreviation is a key. > Then you can just look up the potential key rather than looping thru all the > keys. That is what dictionaries are for!: > > month_dict = {"jan" : 1, > "january" : 1, > "feb" : 2, > "february" :2, etc ...} > ... > except ValueError: > if month.lower() in month_dict: > month = month_dict[month.lower()] > else: > month = "" > > The dict function is also handy here: > > month_dict = dict( > jan = 1, > january = 1, > feb = 2, > february = 2, etc ...) Dear Christopher, Instead of multiplying the keys for each possible version of the written month, I would rather have: month_dict = {"jan":1, "feb":2, ...} and have: written_month = written_month[:3].lower() if written_month in month_dict: # do something Regards, Benoit. From norman at khine.net Thu Aug 7 14:16:49 2008 From: norman at khine.net (Norman Khine) Date: Thu, 7 Aug 2008 14:16:49 +0200 Subject: [Tutor] Merging dictionaries In-Reply-To: <78b3a9580808062353w1f3a390sa01a0de809a595e6@mail.gmail.com> References: <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c@mail.gmail.com> <78b3a9580808062353w1f3a390sa01a0de809a595e6@mail.gmail.com> Message-ID: <9c2c8ffb0808070516q39138fb9u327f825081539ac7@mail.gmail.com> Thank you all for the replies. Norman On 8/7/08, wesley chun <wescpy at gmail.com> wrote: > hmmm, somewhat off-topic, i was partially confused by the Subject > line. i thought this post was about merging *dictionaries* and not > merging the *contents of multiple dictionaries' values*. > > for those who are interested in the former, you use the update() > method and here is an example: > > >>> d1 = dict(zip(range(3), range(3))) > >>> d1 > {0: 0, 1: 1, 2: 2} > >>> d2 = dict(zip(range(2,5), [i*2 for i in range(2, 5)])) > >>> d2 > {2: 4, 3: 6, 4: 8} > >>> d1.update(d2) > >>> d1 > {0: 0, 1: 1, 2: 4, 3: 6, 4: 8} > > notice that the update will replace any existing key with the > corresponding value of the argument dict. > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From srilyk at gmail.com Thu Aug 7 14:42:37 2008 From: srilyk at gmail.com (W W) Date: Thu, 7 Aug 2008 07:42:37 -0500 Subject: [Tutor] iterating data and populating a dictionary In-Reply-To: <376fbdcf0808062242p6066f18bi9d8dbd3b1aedb638@mail.gmail.com> References: <fbf64d2b0808050808u4607f620vc5acb9645d59fb7f@mail.gmail.com> <g7a0dn$q9d$1@ger.gmane.org> <g7ae0l$ce8$1@ger.gmane.org> <376fbdcf0808062242p6066f18bi9d8dbd3b1aedb638@mail.gmail.com> Message-ID: <333efb450808070542l4b5ec788j3fb66845b948f1dc@mail.gmail.com> On Thu, Aug 7, 2008 at 12:42 AM, Shrutarshi Basu <technorapture at gmail.com>wrote: > If you're just going to be using numbers as dictionary keys, it might > be simpler just to use a list structure. Dictionaries don't preserve > order, so you'd need to write extra code if you ever need to iterate > over it in order. It wouldn't be any (or at least much) more difficult than looping over a list of known/unknown length. Known length: for x in range(0, length): do something with mydict[x] Unknown length, dict keys starting at 0: for x in range(0, len(mydict)): do something with mydict[x] Known length, dict keys starting at 1: for x in range(1, (len(mydict)+1)): do something with mydict[x] Probably not the most elegant solution, but it does work. I can't really think of a particular reason it would be useful, though. The main reason a dict is useful is for key values that won't change, and aren't easily kept track of (i.e. names). It's a lot more difficult (at least for the interpreter, as in processor cycles) to find "John Smith" in a list, than to convert it to a hash value and look it up in a hash table. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080807/a4778a23/attachment.htm> From zebra05 at gmail.com Thu Aug 7 15:28:39 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 7 Aug 2008 15:28:39 +0200 Subject: [Tutor] Python and the Global Interpreter Lock Message-ID: <c7c6f3bc0808070628u6d06f463n2bbfea9c9d291dbb@mail.gmail.com> Hi there, I just came across something called the Global Interpreter Lock, and apparently its a condition where an interpreter locks resources to avoid sharing them with other apps/ processes on the system? I wish to find out what this means in terms of Python. for example does it mean that Python cannot take advantage of multiple CPUs? And does it mean that only one interpreter will run per box in a hosting environment? I look forward to enlightenment. Thanks, -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080807/a839e31f/attachment.htm> From lie.1296 at gmail.com Thu Aug 7 15:33:28 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 07 Aug 2008 20:33:28 +0700 Subject: [Tutor] Merging dictionaries In-Reply-To: <mailman.12626.1218086507.920.tutor@python.org> References: <mailman.12626.1218086507.920.tutor@python.org> Message-ID: <1218116008.6357.3.camel@lieryan-laptop> > Message: 4 > Date: Wed, 6 Aug 2008 21:59:40 +0200 > From: "Norman Khine" <norman at khine.net> > Subject: [Tutor] Merging dictionaries > To: tutor at python.org > Message-ID: > <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hello, > I am trying to figure out the best way to add results from a poll > module that I > have working, but am a bit stuck and can't see on how to add the total > responses > submitted by the user. > > So far I have an output which puts in a list all the user's responses, > such as > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, > 3]} .... ] > > Is this an efficient way to do this, say for example I have 1000's of > responses? > > What is the best way to append value items of dictionaries, such that: > > responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1, > 3]}] > > is transformmed into: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} > > I have tried this: > > Type "help", "copyright", "credits" or "license" for more information. > >>> ret = {} > >>> myvalues = [] > >>> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, > 1, 3]}] > >>> for response in responses: > mykeys = [] > for answer in response.items(): > mykeys.append(answer[0]) > for key in mykeys: > if not ret.has_key(key): > ret[key] = [] > else: > ret[key].append(answer[1]) > > >>> print ret > {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} > > But is not correct ;'( You'd want list.extend, not list.append. There is slight difference between list.extend and list.append, extend would iterate through the second list and append each item in the second list to the first list. > > And finally, what is the simplest way to count the nummber of > occurances, so > that: > > answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]} > > returns > > totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]} > > > I tried this: > > ret = {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]} > storage = {} > for code in ret: > for answer, x in questions.items(): > for x in x: > if not storage.has_key(x): > storage[x] = {'count': 1} > else: > storage[x]['count'] += 1 > print storage > > But this did not work either. > > Cheers > > Norman > > From bgailer at gmail.com Thu Aug 7 16:37:14 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 07 Aug 2008 07:37:14 -0700 Subject: [Tutor] Python and the Global Interpreter Lock In-Reply-To: <c7c6f3bc0808070628u6d06f463n2bbfea9c9d291dbb@mail.gmail.com> References: <c7c6f3bc0808070628u6d06f463n2bbfea9c9d291dbb@mail.gmail.com> Message-ID: <489B089A.1030806@gmail.com> OkaMthembo wrote: > Hi there, > > I just came across something called the Global Interpreter Lock, and > apparently its a condition where an interpreter locks resources to > avoid sharing them with other apps/ processes on the system? I wish to > find out what this means in terms of Python. for example does it mean > that Python cannot take advantage of multiple CPUs? And does it mean > that only one interpreter will run per box in a hosting environment? See http://en.wikipedia.org/wiki/Global_Interpreter_Lock. This only applies to threads within a Python process, not other apps/prcoesses. > > I look forward to enlightenment. So do I. Who is your guru? From ssmith46 at zimbra.naz.edu Thu Aug 7 16:55:58 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Thu, 7 Aug 2008 10:55:58 -0400 (EDT) Subject: [Tutor] Python and NT Authentication Message-ID: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> Hello, everyone- I'm trying to both learn Python and develop a fairly robust web form with it at the same time... nothing like being thrown into a new job and having to learn a new language to do it! We have ActiveState Python 2.5 installed on an IIS box running Windows 2003. We're doing it this way because we will most likely be switching to Apache / Unix in the future, and we don't want to have to rewrite all of our server-side scripts. Our web server is a domain member. I am coding a form that will allow authenticated NT users to submit project requests. The form will, among other things, need to pull a list of domain users and put it into a dropdown menu, as well as show the username of the current user. Results will be dumped into an ODBC-connected mySQL database, which is working well (it's just the authentication issue that I'm struggling with). I am able to connect to the domain with the following: <%import ldap, sys, win32api LDAP_SERVER='ldap://nazareth.internal' LDAP_USERNAME='myusername at nazareth.internal' LDAP_PASSWORD='mypassword' try: ldap_client = ldap.initialize(LDAP_SERVER) ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD) except ldap.INVALID_CREDENTIALS, e: Response.Write("<h1 style='color:red'>Invalid credentials</h1>") sys.exit() except ldap.SERVER_DOWN, e: Response.Write("<h1 style='color:red'>Your server appears to be down.</h1>") sys.exit() Response.Write("<h1 style='color:blue'>Connected! All is well.</h1>") ldap_client.unbind() %> However, other than hard-coding the variables, I don't know how to get them from the user, nor do I know how to actually authenticate them. Should I be using Cookies? How is that done? As far as populating the form's <select> dropdown box, I've been using something similar to: <% import pyodbc cnxn_ro = pyodbc.connect("DSN=metaproject_ro") cursor = cnxn_ro.cursor() cursor.execute("select * from Person order by last_name, first_name") for row in cursor: Response.Write("<option value='"+row.uid+"'>"+row.last_name+", "+row.first_name+" ("+row.uid+")</option>") cursor.close() %> (for testing purposes, I actually built a table in the database just so that I could populate it programmatically, but this is where I'd like to pull the info from Active Directory. Hope someone can help! I've been scouring the web for several hours, and I'm actually *more* confused than when I started. Thanks! Steven L Smith Web Developer Nazareth College of Rochester From srilyk at gmail.com Thu Aug 7 18:31:08 2008 From: srilyk at gmail.com (W W) Date: Thu, 7 Aug 2008 11:31:08 -0500 Subject: [Tutor] Fwd: Python and NT Authentication In-Reply-To: <333efb450808070930n78c78acanf6480aa28920689f@mail.gmail.com> References: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> <333efb450808070930n78c78acanf6480aa28920689f@mail.gmail.com> Message-ID: <333efb450808070931t67536c12l3aa686f216bb4e90@mail.gmail.com> (I hate it when I forget to "reply-to all") ---------- Forwarded message ---------- From: W W <srilyk at gmail.com> Date: Thu, Aug 7, 2008 at 11:30 AM Subject: Re: [Tutor] Python and NT Authentication To: Steven L Smith <ssmith46 at naz.edu> On Thu, Aug 7, 2008 at 9:55 AM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > Hello, everyone- > > I'm trying to both learn Python and develop a fairly robust web form with > it at the same time... nothing like being thrown into a new job and having > to learn a new language to do it! > Well, hopefully it won't take you too long to catch on! I personally haven't used Python for doing any web programming, but I know that with PHP you usually use forms (GET or POST) to get the data from the user, and I'm certain you can do similar things with python. I'm sure there are quite a few others here who can help with that, but hopefully that should point you in the right direction! HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080807/3cef2f38/attachment.htm> From cfuller084 at thinkingplanet.net Thu Aug 7 19:08:24 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 7 Aug 2008 12:08:24 -0500 Subject: [Tutor] Python and NT Authentication In-Reply-To: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> References: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <200808071208.24761.cfuller084@thinkingplanet.net> You should search/browse MSDN for authentication info. Also, you can run Apache on windows, if that eases your migration. http://msdn.microsoft.com/en-us/library/aa374735(VS.85).aspx This probably what you want. Just be sure to keep your authentication code as modular as possible, if you are planning to dump a few apple carts as it sounds like you might. I don't know how big a deal it would be to maintain two separate authentication systems, but you might want to consider some other way than going through the win32 api. There might be some way you could use LDAP or such, to ease administration. Stick to open standards and protocols when possible :) Notwithstanding how messy the win32 api is, of course :) Cheers On Thursday 07 August 2008 09:55, Steven L Smith wrote: > Hello, everyone- > > I'm trying to both learn Python and develop a fairly robust web form with > it at the same time... nothing like being thrown into a new job and having > to learn a new language to do it! > > We have ActiveState Python 2.5 installed on an IIS box running Windows > 2003. We're doing it this way because we will most likely be switching to > Apache / Unix in the future, and we don't want to have to rewrite all of > our server-side scripts. Our web server is a domain member. > > I am coding a form that will allow authenticated NT users to submit project > requests. The form will, among other things, need to pull a list of domain > users and put it into a dropdown menu, as well as show the username of the > current user. Results will be dumped into an ODBC-connected mySQL database, > which is working well (it's just the authentication issue that I'm > struggling with). > > I am able to connect to the domain with the following: > > <%import ldap, sys, win32api > LDAP_SERVER='ldap://nazareth.internal' > LDAP_USERNAME='myusername at nazareth.internal' > LDAP_PASSWORD='mypassword' > > try: > ldap_client = ldap.initialize(LDAP_SERVER) > ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD) > > except ldap.INVALID_CREDENTIALS, e: > Response.Write("<h1 style='color:red'>Invalid credentials</h1>") > sys.exit() > except ldap.SERVER_DOWN, e: > Response.Write("<h1 style='color:red'>Your server appears to be > down.</h1>") sys.exit() > > Response.Write("<h1 style='color:blue'>Connected! All is well.</h1>") > ldap_client.unbind() > %> > > However, other than hard-coding the variables, I don't know how to get them > from the user, nor do I know how to actually authenticate them. Should I be > using Cookies? How is that done? > > As far as populating the form's <select> dropdown box, I've been using > something similar to: > > <% > import pyodbc > cnxn_ro = pyodbc.connect("DSN=metaproject_ro") > cursor = cnxn_ro.cursor() > cursor.execute("select * from Person order by last_name, first_name") > for row in cursor: > Response.Write("<option value='"+row.uid+"'>"+row.last_name+", > "+row.first_name+" ("+row.uid+")</option>") cursor.close() > %> > > (for testing purposes, I actually built a table in the database just so > that I could populate it programmatically, but this is where I'd like to > pull the info from Active Directory. > > > > Hope someone can help! I've been scouring the web for several hours, and > I'm actually *more* confused than when I started. > > > Thanks! > > > Steven L Smith > Web Developer > Nazareth College of Rochester > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rdmoores at gmail.com Thu Aug 7 18:54:34 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 09:54:34 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py In-Reply-To: <489A3D2B.1020603@aon.at> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> Message-ID: <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> On Wed, Aug 6, 2008 at 5:09 PM, Gregor Lingl <gregor.lingl at aon.at> wrote: > This is due to a bug in turtle.py - interestingly after so many years of use > and improvement of turtle.py there still appear new bugs from time to time. > > The bug consists in a missing update of the Canvas in the fill() function > You can repair it by inserting a line at line#309 in turtle.py in the > fill method as follows: > > if self._filling: > path = tuple(self._path) > smooth = self._filling < 0 > if len(path) > 2: > item = self._canvas._create('polygon', path, > {'fill': self._color, > 'smooth': smooth}) > self._items.append(item) > self._canvas.update() # <=== bug-fix > self._path = [] > > Now for the good news: > > (1) If you have done this, not only Dick's program works as > intended, Yes, it does! I've pasted a version at <http://py77.python.pastebin.com/f228f64f>. Thank you! > (2) Python 2.6 will have a new turtle module - formerly known to some > as xturtle.py - which has much more capabilities and which at least doesn't > show > this bug. Presumably there will appear others, especially in the beginning > of > it's use. It is contained in Python2.6 beta2, it runs also under Python2.5 > and it should be (nearly?) 100%-compatible with the old turtle module. > > Its documentation can be found here: > http://docs.python.org/dev/library/turtle.html#module-turtle > > It would be really very helpful, if those of you who use to use turtle > graphcis would work with this new module in order to reveal as many > bugs as possible before the final release of Python 2.6 scheduled for > early october 2008. I got Python2.6 beta2 and copied its turtle.py to my Python 2.5 after renaming it turtle26.py. By now I've spent several hours trying to figure out how to get my program to work well with it. I don't know if I've discovered any bugs, but here are some of the problems I have: 1. The turtle has some behavior I don't see how to eliminate. If you refer to lines 223, 225, 227, 229, etc., you'll see that the turtle always faces in the direction it is moving when drawing a rectangle. Using the Python2.6 beta2 version of turtle.py, the turtle can be seen at each corner spinning to orient itself to the new direction. I don't want this. I thought I could remove the spinning effect by setting the turtle's shape to a circle. But the circle is way bigger than the default turtle. No spinning, but not what I'm after. 2. The turtle can also be seen moving from the last corner of the last rectangle to the first corner of the next. I don't want this. 3. When the screen is cleared between cycles by line 367, the blank screen shows for a second or so. I don't want this. In my program using the old turtle I've had to create colored-backgrounds by drawing a rectangle almost as large as the screen (see my draw_background() beginning at line 365). With the new turtle, the background color can be set by, for example, screen.bgcolor("orange"). But even so, in the V16 I was trying to write, that blank screen still shows for a second or so. With the old turtle, the transition from one "background" to another seems instantaneous. No white blank screen visible at all. 4. I've attempted to make the turtle invisible, but haven't succeeded. I'm guessing that all the problems I've mentioned aren't the result of bugs--rather, I just don't understand the doc. > Of course I'd assist if questions or problems would arise. Thanks. Dick From rdmoores at gmail.com Thu Aug 7 20:02:23 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 11:02:23 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by a bug in turtle.py In-Reply-To: <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> Message-ID: <d71c7ed60808071102i6ccad5afs6287f7cd9611a510@mail.gmail.com> On Thu, Aug 7, 2008 at 9:54 AM, Dick Moores <rdmoores at gmail.com> wrote: > 4. I've attempted to make the turtle invisible, but haven't succeeded. Got it! hideturtle() <http://docs.python.org/dev/library/turtle.html#turtle.hideturtle> Dick From alan.gauld at btinternet.com Thu Aug 7 20:26:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Aug 2008 19:26:31 +0100 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com><1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com><489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> Message-ID: <g7feoq$co0$1@ger.gmane.org> "Dick Moores" <rdmoores at gmail.com> wrote > 1. The turtle has some behavior I don't see how to eliminate. If you > refer to lines 223, 225, 227, 229, etc., you'll see that the turtle > always faces in the direction it is moving when drawing a rectangle. That is correct behaviour for a turtle! Remember turtle graphics are notionally about moving a physical drawing device (the turtle) around on the floor or desk. If the turtle doesn't turn to face the direction of travel it can't travel that way! IMHO that's just a feature of the technology and any other behaviour would be out of keeping with the intent. > Using the Python2.6 beta2 version of turtle.py, the turtle can be > seen > at each corner spinning to orient itself to the new direction. I > don't > want this. While far from common in turtle implementations (I have only seen it in my old CP/M Logo version) it is a feature that would be true of a physical turtle too. Its not really a bug but a "feature" I guess! > 2. The turtle can also be seen moving from the last corner of the > last > rectangle to the first corner of the next. I don't want this. Again true of a physical turtle... But if you set speed to fastest does that work? Also in the old turtle moduile there was a way to hide the turtles movements completely and just draw the finished graphic - which was orders of magnitude faster for complex shapes - is that still available in turtle26? One way to hide the turtle would be top change colour to the background color. That would make themoving turtle invisible... > 3. When the screen is cleared between cycles by line 367, the blank > screen shows for a second or so. I don't want this. > In my program using the old turtle I've had to create > colored-backgrounds by drawing a rectangle almost as large as the > screen (see my draw_background() beginning at line 365). With the > new > turtle, the background color can be set by, for example, > screen.bgcolor("orange"). But even so, in the V16 I was trying to > write, that blank screen still shows for a second or so. With the > old > turtle, the transition from one "background" to another seems > instantaneous. No white blank screen visible at all. Sounds like a valid complaint that one... > 4. I've attempted to make the turtle invisible, but haven't > succeeded. Should be possible to set color to bgcolor. but set it back to draw the lines or they too will be invisible! > I'm guessing that all the problems I've mentioned aren't the result > of > bugs--rather, I just don't understand the doc. Matybe more not understanding(remembering) the origin of turtle graphics. It was for kids to understand computer graphics... Seeing the shapes being drawn is a big part of that. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 7 20:31:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Aug 2008 19:31:39 +0100 Subject: [Tutor] Python and NT Authentication References: <774544343.6267641218120958101.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <g7ff2e$dtr$1@ger.gmane.org> "Steven L Smith" <ssmith46 at zimbra.naz.edu> wrote in > We have ActiveState Python 2.5 installed on an IIS box running > Windows 2003. We're doing it this way because we will most > likely be switching to Apache / Unix in the future, and we > don't want to have to rewrite all of our server-side scripts. ... > <%import ldap, sys, win32api > LDAP_SERVER='ldap://nazareth.internal' > LDAP_USERNAME='myusername at nazareth.internal' > LDAP_PASSWORD='mypassword' It looks like you are using Active Scripting for the web pages? That probably won't work on Unix/Apache, it might be better to use CGI or one of the web frameworks that will be portable across web servers as well as across OS. Nothing to do with your query but an observation... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dave6502 at googlemail.com Thu Aug 7 23:25:53 2008 From: dave6502 at googlemail.com (dave selby) Date: Thu, 7 Aug 2008 22:25:53 +0100 Subject: [Tutor] Split string on 2 delimiters ? Message-ID: <f52017b60808071425y5f282e3cncffe81780e6a10b@mail.gmail.com> Hi all, Is there a neat way to split a string on either of two delimiters ie space and comma Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From timothy.grant at gmail.com Thu Aug 7 23:36:28 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 7 Aug 2008 14:36:28 -0700 Subject: [Tutor] Split string on 2 delimiters ? In-Reply-To: <f52017b60808071425y5f282e3cncffe81780e6a10b@mail.gmail.com> References: <f52017b60808071425y5f282e3cncffe81780e6a10b@mail.gmail.com> Message-ID: <e775286d0808071436s5d0024cfj6ca9df1db6cc9339@mail.gmail.com> On Thu, Aug 7, 2008 at 2:25 PM, dave selby <dave6502 at googlemail.com> wrote: > Hi all, > > Is there a neat way to split a string on either of two delimiters ie > space and comma > > Cheers > > Dave >>> import re >>> string = 'this is, a test of splitting; on two delimiters' >>> re.split(r'[,;]', string) ['this is', ' a test of splitting', ' on two delimiters'] >>> re.split(r'[, ]', string) ['this', 'is', '', 'a', 'test', 'of', 'splitting;', 'on', 'two', 'delimiters'] -- Stand Fast, tjg. [Timothy Grant] From kent37 at tds.net Thu Aug 7 23:42:00 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 7 Aug 2008 17:42:00 -0400 Subject: [Tutor] Split string on 2 delimiters ? In-Reply-To: <f52017b60808071425y5f282e3cncffe81780e6a10b@mail.gmail.com> References: <f52017b60808071425y5f282e3cncffe81780e6a10b@mail.gmail.com> Message-ID: <1c2a2c590808071442n273951f8l8bfbde83df55078e@mail.gmail.com> On Thu, Aug 7, 2008 at 5:25 PM, dave selby <dave6502 at googlemail.com> wrote: > Hi all, > > Is there a neat way to split a string on either of two delimiters ie > space and comma Use re.split(): In [1]: import re In [2]: data = 'tom,dick harry' In [4]: re.split(r'[, ]', data) Out[4]: ['tom', 'dick', 'harry'] Since you have the full power of re to match your delimiter you could for example allow comma, space or both: In [6]: re.split(r', *| +', 'tom, dick,harry and bill') Out[6]: ['tom', 'dick', 'harry', 'and', 'bill'] Kent From rdmoores at gmail.com Thu Aug 7 23:44:02 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 14:44:02 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <g7feoq$co0$1@ger.gmane.org> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> Message-ID: <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld <alan.gauld at btinternet.com> wrote: > "Dick Moores" <rdmoores at gmail.com> wrote > >> 1. The turtle has some behavior I don't see how to eliminate. If you >> refer to lines 223, 225, 227, 229, etc., you'll see that the turtle >> always faces in the direction it is moving when drawing a rectangle. > > That is correct behaviour for a turtle! Yes. I wanted that, and set it accordingly. Those lines refer to the program using the 2.5 turtle.py. > Remember turtle graphics are notionally about moving a physical > drawing device (the turtle) around on the floor or desk. If the turtle > doesn't turn to face the direction of travel it can't travel that way! > > IMHO that's just a feature of the technology and any other behaviour > would be out of keeping with the intent. Actually, if you look at those lines, I had to go to some trouble to get the turtle to do that! >> Using the Python2.6 beta2 version of turtle.py, the turtle can be seen >> at each corner spinning to orient itself to the new direction. I don't >> want this. > > While far from common in turtle implementations (I have only seen > it in my old CP/M Logo version) it is a feature that would be true > of a physical turtle too. Its not really a bug but a "feature" I guess! I finally found how to make the turtle disappear permanently. In the new turtle.py, the code is "hideturtle()". >> 2. The turtle can also be seen moving from the last corner of the last >> rectangle to the first corner of the next. I don't want this. > > Again true of a physical turtle... But if you set speed to fastest > does that work? Also in the old turtle moduile there was a way to > hide the turtles movements completely and just draw the finished > graphic - which was orders of magnitude faster for complex > shapes - is that still available in turtle26? Yes, penup(). <http://docs.python.org/dev/library/turtle.html#turtle.penup> > One way to hide the turtle would be top change colour to the Thanks for thinking about it, but with hideturtle() I'm a happy camper. >> 3. When the screen is cleared between cycles by line 367, the blank >> screen shows for a second or so. I don't want this. >> In my program using the old turtle I've had to create >> colored-backgrounds by drawing a rectangle almost as large as the >> screen (see my draw_background() beginning at line 365). With the new >> turtle, the background color can be set by, for example, >> screen.bgcolor("orange"). But even so, in the V16 I was trying to >> write, that blank screen still shows for a second or so. With the old >> turtle, the transition from one "background" to another seems >> instantaneous. No white blank screen visible at all. Solved that. I'm pasting the version that uses the new turtle.py. <http://py77.python.pastebin.com/f657deaaf>. This runs fine, but I'll be doing more work on it. > Sounds like a valid complaint that one... >> 4. I've attempted to make the turtle invisible, but haven't succeeded. See above. > Should be possible to set color to bgcolor. but set it back to > draw the lines or they too will be invisible! > >> I'm guessing that all the problems I've mentioned aren't the result of >> bugs--rather, I just don't understand the doc. > > Maybe more not understanding(remembering) the origin of turtle graphics. > It was for kids to understand computer graphics... Seeing the shapes > being drawn is a big part of that. Well, I also want to see the rectangles being drawn--by an invisible turtle. ;-) Actually, I got interested in this because of the colors. I had just bought my first LCD monitor, a 22-incher. And I wrote the program so that it prints the color names to the console window. I had been ignorant about colors--had no idea what magenta, chartreuse, turquoise, cyan were, just to mention a few. Thanks, Alan. Dick From gregor.lingl at aon.at Fri Aug 8 00:47:54 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 00:47:54 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() In-Reply-To: <g7feoq$co0$1@ger.gmane.org> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com><1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com><489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> Message-ID: <489B7B9A.6090109@aon.at> Alan Gauld schrieb: > "Dick Moores" <rdmoores at gmail.com> wrote > >> 1. The turtle has some behavior I don't see how to eliminate. If you >> refer to lines 223, 225, 227, 229, etc., you'll see that the turtle >> always faces in the direction it is moving when drawing a rectangle. > > That is correct behaviour for a turtle! > Remember turtle graphics are notionally about moving a physical > drawing device (the turtle) around on the floor or desk. If the turtle > doesn't turn to face the direction of travel it can't travel that way! > > IMHO that's just a feature of the technology and any other behaviour > would be out of keeping with the intent. > Hi all, development of this rectangle pattern program is going verry fast and as I see Dick has managed to abridge his program by some fifty lines (using the new turtle module). Most of his questions got superb answers by Alan, so I'll add only a few remarks: In fact Dick doesn't use any turtle graphics functions in it's precise original meaning. Instead he uses a (global) Cartesian coordinate system and moves the turtle only by calling goto(). (This approach is perfectly ok for his task, of course). Turtle graphics by contrast uses a local coordinate system of the "turtle" and moves it by calling only forward(), back(), left() and right() functions. >> Using the Python2.6 beta2 version of turtle.py, the turtle can be seen >> at each corner spinning to orient itself to the new direction. I don't >> want this. So you eliminated the superfluous setheading() calls. > > While far from common in turtle implementations (I have only seen > it in my old CP/M Logo version) it is a feature that would be true > of a physical turtle too. Its not really a bug but a "feature" I guess! > >> 2. The turtle can also be seen moving from the last corner of the last >> rectangle to the first corner of the next. I don't want this. This is ideed an intended difference between the new and the old turtle module. I consider this to be an improvement of the animation of the turtle. (You can observe another improvement by trying out e. g. left(1080) ) The intention is that the beginning programmer can visually observe what he or she has programmed and thus more easily identify errors in his/her program. To that end the turtle moves and turns at the specified speed regardless of the state of the pen (up or down). If you don't like this you can set speed to 0 which - paradoxically - means that the animation is turned off and the turtle jumps instantaneously. (Think of something like speed(False)) > Again true of a physical turtle... But if you set speed to fastest > does that work? Yes, that is speed(0). See above > Also in the old turtle moduile there was a way to > hide the turtles movements completely and just draw the finished > graphic - which was orders of magnitude faster for complex > shapes - is that still available in turtle26? Yes it is (of course ;-) ). Use tracer in the same way as in the old one. > > > One way to hide the turtle would be top change colour to the > background color. That would make themoving turtle invisible... > As Dick discoverd you can use hideturtle() and showturtle() >> 3. When the screen is cleared between cycles by line 367, the blank >> screen shows for a second or so. I don't want this. >> In my program using the old turtle I've had to create >> colored-backgrounds by drawing a rectangle almost as large as the >> screen (see my draw_background() beginning at line 365). With the new >> turtle, the background color can be set by, for example, >> screen.bgcolor("orange"). But even so, in the V16 I was trying to >> write, that blank screen still shows for a second or so. With the old >> turtle, the transition from one "background" to another seems >> instantaneous. No white blank screen visible at all. > > Sounds like a valid complaint that one... This again is a result of the animation of the turtle. Of course a correct use of bgcolor() solves this problem - as Dick did now -, but also use of speed(0) or tracer(False) would have solved it. Regards, Gregor P.S.: If you are interested, you can download a series of sample programs covering a broad range from very easy to fairly advanced, which intend to show some features and capabilities of the new turtle module from here: http://svn.python.org/view/python/trunk/Demo/turtle/ These will be included in the source distribution - but not in the Windows installer. From gregor.lingl at aon.at Fri Aug 8 01:04:14 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 01:04:14 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> Message-ID: <489B7F6E.6010205@aon.at> Hi Dick, first of all, thanks for your efforts using the new turtle module and reporting about your experiences and the problems you ran into. I've already made some remarks on it in a former reply in this thread. > On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld <alan.gauld at btinternet.com> wrote: > > ... >>> 2. The turtle can also be seen moving from the last corner of the last >>> rectangle to the first corner of the next. I don't want this. >>> >> Again true of a physical turtle... But if you set speed to fastest >> does that work? Also in the old turtle moduile there was a way to >> hide the turtles movements completely and just draw the finished >> graphic - which was orders of magnitude faster for complex >> shapes - is that still available in turtle26? >> Here better tracer() should come in! > Yes, penup(). <http://docs.python.org/dev/library/turtle.html#turtle.penup> > >> >> Maybe more not understanding(remembering) the origin of turtle graphics. >> It was for kids to understand computer graphics... Seeing the shapes >> being drawn is a big part of that. >> That's why now turtles have got a better animation. (That means: the resulting drawing should be the same weather you use the old module or the new one, but *not* what you see, when you observe the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of course, the now one has a lot of additional enhacements.) Best regards, Gregor > Well, I also want to see the rectangles being drawn--by an invisible turtle. ;-) > > Actually, I got interested in this because of the colors. I had just > bought my first LCD monitor, a 22-incher. And I wrote the program so > that it prints the color names to the console window. I had been > ignorant about colors--had no idea what magenta, chartreuse, > turquoise, cyan were, just to mention a few. > > Thanks, Alan. > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From rdmoores at gmail.com Fri Aug 8 02:38:00 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 17:38:00 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <489B7F6E.6010205@aon.at> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> <489B7F6E.6010205@aon.at> Message-ID: <d71c7ed60808071738w5cd184e8hbe07fe69bfb3d42e@mail.gmail.com> On Thu, Aug 7, 2008 at 4:04 PM, Gregor Lingl <gregor.lingl at aon.at> wrote: > Hi Dick, > > first of all, thanks for your efforts using the new turtle module > and reporting about your experiences and the problems you ran into. Sure. And I'm not finished. There seem to be some interesting new things worth investigating. > I've already made some remarks on it in a former reply in this thread. Yes. Thanks. >> On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld <alan.gauld at btinternet.com> >> wrote: >> ... >>>> >>>> 2. The turtle can also be seen moving from the last corner of the last >>>> rectangle to the first corner of the next. I don't want this. >>>> >>> >>> Again true of a physical turtle... But if you set speed to fastest >>> does that work? Also in the old turtle moduile there was a way to >>> hide the turtles movements completely and just draw the finished >>> graphic - which was orders of magnitude faster for complex >>> shapes - is that still available in turtle26? >>> > > Here better tracer() should come in! 'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it. http://docs.python.org/dev/library/turtle.html#turtle.tracer >> Yes, penup(). >> <http://docs.python.org/dev/library/turtle.html#turtle.penup> >> >>> >>> Maybe more not understanding(remembering) the origin of turtle graphics. >>> It was for kids to understand computer graphics... Seeing the shapes >>> being drawn is a big part of that. >>> > > That's why now turtles have got a better animation. (That means: the > resulting drawing should be > the same weather you use the old module or the new one, but *not* what you > see, when you observe > the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of > course, the now one > has a lot of additional enhacements.) And I'm going to have questions! Already have one. What is tracer()? Thanks for these: <http://svn.python.org/view/python/trunk/Demo/turtle/> And clock.py uses tracer(), so cancel that question. Obvious. Dick =================================================== Have you seen Kelie Feng's video introducing the terrific and free IDE, Ulipad? <http://www.rcblue.com/u3/> Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list> svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/> Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad> From rdmoores at gmail.com Fri Aug 8 04:23:08 2008 From: rdmoores at gmail.com (Dick Moores) Date: Thu, 7 Aug 2008 19:23:08 -0700 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <489B7F6E.6010205@aon.at> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> <489B7F6E.6010205@aon.at> Message-ID: <d71c7ed60808071923w131d338dmf2e6af5ab1676728@mail.gmail.com> On Thu, Aug 7, 2008 at 4:04 PM, Gregor Lingl <gregor.lingl at aon.at> wrote: > Hi Dick, > > first of all, thanks for your efforts using the new turtle module > and reporting about your experiences and the problems you ran into. Sure. And I'm not finished. There seem to be some interesting new things worth investigating. > I've already made some remarks on it in a former reply in this thread. Yes. Thanks. >> On Thu, Aug 7, 2008 at 11:26 AM, Alan Gauld <alan.gauld at btinternet.com> >> wrote: >> ... >>>> >>>> 2. The turtle can also be seen moving from the last corner of the last >>>> rectangle to the first corner of the next. I don't want this. >>>> >>> >>> Again true of a physical turtle... But if you set speed to fastest >>> does that work? Also in the old turtle moduile there was a way to >>> hide the turtles movements completely and just draw the finished >>> graphic - which was orders of magnitude faster for complex >>> shapes - is that still available in turtle26? >>> > > Here better tracer() should come in! 'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it. http://docs.python.org/dev/library/turtle.html#turtle.tracer >> Yes, penup(). >> <http://docs.python.org/dev/library/turtle.html#turtle.penup> >> >>> >>> Maybe more not understanding(remembering) the origin of turtle graphics. >>> It was for kids to understand computer graphics... Seeing the shapes >>> being drawn is a big part of that. >>> > > That's why now turtles have got a better animation. (That means: the > resulting drawing should be > the same weather you use the old module or the new one, but *not* what you > see, when you observe > the turtles at work. Therfore I wrote (nearly?) 100% compatible. And of > course, the now one > has a lot of additional enhacements.) And I'm going to have questions! Already have one. What is tracer()? Thanks for these: <http://svn.python.org/view/python/trunk/Demo/turtle/> Dick =================================================== Have you seen Kelie Feng's video introducing the terrific and free IDE, Ulipad? <http://www.rcblue.com/u3/> Get Ulipad 3.9 from <http://code.google.com/p/ulipad/downloads/list> svn for the latest revision <http://ulipad.googlecode.com/svn/trunk/> Mailing list for Ulipad: <http://groups-beta.google.com/group/ulipad> From cspears2002 at yahoo.com Fri Aug 8 07:34:05 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 7 Aug 2008 22:34:05 -0700 (PDT) Subject: [Tutor] date formatter In-Reply-To: <78b3a9580808062339s464cfbdep40e720179ee774e9@mail.gmail.com> Message-ID: <762599.20477.qm@web51611.mail.re2.yahoo.com> Ok, here is the working version of my program. Thanks for all of the advice: #!/usr/bin/python import time class date_format(object): def __init__(self, month, day, year): month_dict = {("jan","january") : 1, ("feb","february") :2, ("mar", "march") : 3, ("apr", "april") : 4, ("may",) : 5, ("jun", "june") : 6, ("jul", "july") : 7, ("aug", "august") : 8, ("sep", "september") : 9, ("oct", "october"): 10, ("nov", "november"): 11, ("dec", "december"): 12 } try: month_number = int(month) except ValueError: for eachKey in month_dict.keys(): if month.lower() in eachKey: month_number = month_dict[eachKey] break else: month_number = 0 if month_number==0 or day=="" or year=="": self.date = time.localtime() else: self.date = (int(year), month_number, int(day), 0, 0, 0, 0, 1, -1) def display(self, format_indicator = None): if format_indicator == 'MDY': print time.strftime("%m/%d/%y",self.date) elif format_indicator == 'MDYY': print time.strftime("%m/%d/%Y",self.date) elif format_indicator == 'DMY': print time.strftime("%d/%m/%y",self.date) elif format_indicator == 'DMYY': print time.strftime("%d/%m/%Y",self.date) elif format_indicator == 'MODYY': print time.strftime("%b %d, %Y",self.date) else: print time.strftime("%a %b %d %Y",self.date) if __name__ == "__main__": print "Welcome to the Date Formatter!" month = raw_input("Please enter a month (as a number): ") day = raw_input("Please enter a day: ") year = raw_input("Please enter a year: ") date_obj = date_format(month, day, year) format_indicator = raw_input("Enter a format indicator: ") date_obj.display(format_indicator.upper()) --- On Wed, 8/6/08, wesley chun <wescpy at gmail.com> wrote: > From: wesley chun <wescpy at gmail.com> > Subject: Re: [Tutor] date formatter > To: cspears2002 at yahoo.com > Cc: tutor at python.org > Date: Wednesday, August 6, 2008, 11:39 PM > > try: > > month = int(month) > > except ValueError: > > for eachKey in > month_dict.keys(): > > if month.lower() in > eachKey: > > month = > month_dict[eachKey] > > else: > > month = > "" > > : > > I am having trouble dealing with the case where the > user actually types in a month's name instead of the > number: > > io at io-station-1 ./chap13 180> python > date_format_v01.py > > : > > if month.lower() in eachKey: > > AttributeError: 'int' object has no attribute > 'lower' > > > > Any suggestions? > > > chris, > > good 1st attempt. all the problems are in the code snippet > above. you > only have a few flaws in your program preventing it from > working: > > a. you "wipe out" the originally entered month > (by continually > reassigning the month var) > > b. you don't break out of the inner for-loop when u > find a match and > end up wiping out the correct match > > c. the cause of the exception: the entry for May is a > string and not a > 1-item tuple. you need a trailing comma "," after > "may" to make it a > tuple. the reason why the error is triggered is because > you set a > blank to month for every non-match. so when it gets to may, > it makes > this comparison: > > >>> "" in "may" > True > > because of this, it sets... > > month = month_dict["may"] # so month == 5 > > so in the next loop iteration, your're trying to do... > > 5.lower() in eachKey > > which of course, fails. fix these problems, and you have a > working solution! > > best of luck! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Python Web Development with Django", Addison > Wesley, (c) 2008 > http://withdjango.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com From gregor.lingl at aon.at Fri Aug 8 09:36:01 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 09:36:01 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <d71c7ed60808071738w5cd184e8hbe07fe69bfb3d42e@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> <489B7F6E.6010205@aon.at> <d71c7ed60808071738w5cd184e8hbe07fe69bfb3d42e@mail.gmail.com> Message-ID: <489BF761.1060805@aon.at> Dick Moores schrieb: >> >> Here better tracer() should come in! >> > > 'Deprecated in version 2.6'?? And the doc gives nary a clue how to use it. > http://docs.python.org/dev/library/turtle.html#turtle.tracer > tracer is only deprecated as a Turtle-method, because it doesn't concern single turtles but all the turtles on the screen. It will stay as Screen-method and of course also as function. (As a turtle-method it's only there because of compatibility with the old turtle module.) Gregor From gregor.lingl at aon.at Fri Aug 8 09:39:55 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 09:39:55 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - Important note! In-Reply-To: <489B7B9A.6090109@aon.at> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com><1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com><489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> <489B7B9A.6090109@aon.at> Message-ID: <489BF84B.9000409@aon.at> > > P.S.: If you are interested, you can download a series of sample programs > covering a broad range from very easy to fairly advanced, which > intend to show some features and capabilities of the new turtle module > from here: > > http://svn.python.org/view/python/trunk/Demo/turtle/ > > These will be included in the source distribution - but not in the > Windows > installer. > > IMPORTANT NOTE! In order to have the examples working correctly you have to have turtle.cfg in the directory where the example scripts are (or in that with turtle.py). An easy way to have a look at all the examplescripts is using turtleDemo.py Gregor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From federo at email.si Fri Aug 8 11:12:18 2008 From: federo at email.si (Federo) Date: Fri, 08 Aug 2008 11:12:18 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> Message-ID: <20080808091219.22A228B9F2@www1.email.si> Kent hi I am still unable to enter data into textbox and getting back server reply. The main problem is that I do not understand which fileds / header to observer using Firefox Fireburg. Atteched you can see headers I went through. With red font I marked differences among stages. In nider of the headers I didn't find fieldds you included in your workable login code. Questions: 1.) Could you send print screens of what you are using in Firefox Fireburg 2.) In case I am using the currect headres, I would appreciate you mark on the attached document with pink font important fields to be included in the code in order to be able to get data from server. 3.) The most usefull (the quickest to understand and re-use) would be if you coud make workable code to get server reply for XSNX stock ticker(on screen top left corner: field Symbol - enter XSNX). Once I would see this I would be able to adjust other searches by myselves. This would be realy usefull knowledge. At the moment I am able to do web control with iMacro only. I would like to switch to Python! Login - fake account https://investor.firstrade.com/firstrade/login.do User: janezfedero Pass: kmet555 Side where stock to enter stock Symbole: https://investor.firstrade.com/firstrade/mainmenu.do Workable login code: (The code open main side on which stock symbol can be entered. The question is how to what fields form header to be used and how to put this in the code. Headers can be seen in the attached word file) import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet555', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() # print(data) f = opener.open('https://investor.firstrade.com/firstrade/stockorder.do', params) data = f.read() f.close() print(data) On Mon, 4 Aug 2008 at 16:08:33, Kent Johnson wrote: > On Mon, Aug 4, 2008 at 8:05 AM, Federo <federo at email.si> wrote: > > Kent THANKS! It works great also on real account .. > > > > Two important Sub-QUESTIONS: > > > > 1.) Look attached word file. It describes form fields I would like to fill > in > > and read server resoult.. > > You just have to mimic what the browser does. Use a Firefox plugin > that shows you what is being submitted; TamperData is one. Then set > the same fields in your code. > > > 2.) Could you do the same login logic also with MECHANIZE plagin. There > are > > some very usefull function in this plagin I might use. However I have > > No, I'm not familiar with mechanize. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_Note.rtf Type: application/msword Size: 33888 bytes Desc: FormManagement_Note.rtf URL: <http://mail.python.org/pipermail/tutor/attachments/20080808/fe6d36ef/attachment-0001.wiz> From kent37 at tds.net Fri Aug 8 13:49:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 07:49:06 -0400 Subject: [Tutor] date formatter In-Reply-To: <762599.20477.qm@web51611.mail.re2.yahoo.com> References: <78b3a9580808062339s464cfbdep40e720179ee774e9@mail.gmail.com> <762599.20477.qm@web51611.mail.re2.yahoo.com> Message-ID: <1c2a2c590808080449v48486405yaa7d02cd2975a7db@mail.gmail.com> On Fri, Aug 8, 2008 at 1:34 AM, Christopher Spears <cspears2002 at yahoo.com> wrote: > Ok, here is the working version of my program. Thanks for all of the advice: > > #!/usr/bin/python > > import time > > class date_format(object): This is a bit of a misnomer, you aren't formatting the date, you are parsing it. > def __init__(self, month, day, year): > month_dict = {("jan","january") : 1, > ("feb","february") :2, > ("mar", "march") : 3, > ("apr", "april") : 4, > ("may",) : 5, > ("jun", "june") : 6, > ("jul", "july") : 7, > ("aug", "august") : 8, > ("sep", "september") : 9, > ("oct", "october"): 10, > ("nov", "november"): 11, > ("dec", "december"): 12 > } > > try: > month_number = int(month) > except ValueError: > for eachKey in month_dict.keys(): > if month.lower() in eachKey: > month_number = month_dict[eachKey] > break month_dict might as well be a list, you aren't using the dict-ness of it at all. months = [ (("jan","january") , 1), ... ] try: month_number = int(month) except ValueError: for names, number in months(): if month.lower() in names: month_number = number break else: month_number = 0 You might be interested in this project: http://code-bear.com/code/parsedatetime/ Kent From kent37 at tds.net Fri Aug 8 13:54:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 07:54:41 -0400 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <20080808091219.22A228B9F2@www1.email.si> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> <20080808091219.22A228B9F2@www1.email.si> Message-ID: <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> On Fri, Aug 8, 2008 at 5:12 AM, Federo <federo at email.si> wrote: > Kent hi > > I am still unable to enter data into textbox and getting back server reply. The > main problem is that I do not understand which fileds / header to observer > using Firefox Fireburg. Atteched you can see headers I went through. With red > font I marked differences among stages. In nider of the headers I didn't find > fieldds you included in your workable login code. Hi Federo, This isn't really a Python question anymore, it is a matter of figuring out what the server requires. You have to look at the form data as well as the headers. TamperData is one Firefox pluging that can do that, I'm sure there are others as well. Kent From spython01 at gmail.com Fri Aug 8 17:56:27 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 11:56:27 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays Message-ID: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> Hi Everyone, I would like to create a two-dimensional array but am confused as to how to go about it. I've read about Numeric Python and Numpy. Are they one and the same? Also, how do I install them? I am working on a Windows machine. I've been getting the following error messages: >>> import Numeric Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> import Numeric ImportError: No module named Numeric >>> from Numeric import * Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> from Numeric import * ImportError: No module named Numeric I then downloaded and installed release 1.1.1 of the Numpy package from this site: http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 After restarting the shell, I still get the same errors above (though I do have this directory now: C:\Python25\Lib\site-packages\numpy). Anyone know how to correctly install and use this package? Thanks in advance. Samir From kent37 at tds.net Fri Aug 8 18:25:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 12:25:11 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> Message-ID: <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> On Fri, Aug 8, 2008 at 11:56 AM, S Python <spython01 at gmail.com> wrote: > Hi Everyone, > > I would like to create a two-dimensional array but am confused as to > how to go about it. > > I've read about Numeric Python and Numpy. Are they one and the same? No, they are not the same. Numeric is older; NumArray is another older package. You should use Numpy if you can. http://numpy.scipy.org/#older_array > I then downloaded and installed release 1.1.1 of the Numpy package > from this site: > http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=175103 > > After restarting the shell, I still get the same errors above (though > I do have this directory now: C:\Python25\Lib\site-packages\numpy). > > Anyone know how to correctly install and use this package? Now you should be able to import numpy. Kent From spython01 at gmail.com Fri Aug 8 18:29:53 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 12:29:53 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> Message-ID: <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> > No, they are not the same. Numeric is older; NumArray is another older > package. You should use Numpy if you can. > http://numpy.scipy.org/#older_array > <snip> > > Now you should be able to import numpy. > > Kent > Thanks, Kent. I ended up using: >>> from numpy import * I wasn't sure what the difference was between this and >>> import numpy Thanks! Samir From timothy.grant at gmail.com Fri Aug 8 19:25:43 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 8 Aug 2008 10:25:43 -0700 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> Message-ID: <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> On Fri, Aug 8, 2008 at 9:29 AM, S Python <spython01 at gmail.com> wrote: >> No, they are not the same. Numeric is older; NumArray is another older >> package. You should use Numpy if you can. >> http://numpy.scipy.org/#older_array >> > <snip> >> >> Now you should be able to import numpy. >> >> Kent >> > > Thanks, Kent. I ended up using: >>>> from numpy import * > > I wasn't sure what the difference was between this and >>>> import numpy > > Thanks! > > Samir In general "from <module> import *" is a very bad idea. import <module> imports a module into its own namespace (e.g., to access its functionality you would have to do "<module>.foo() and <module>.bar()" The form that you chose to use imports all of a module's contents into the current namespace. This means you can call "foo()" and "bar()" directly, but it also means that if you have coded a "foo()" and a "bar()" you will not have access to the functions in the module you just imported. -- Stand Fast, tjg. [Timothy Grant] From rambert.marc at free.fr Fri Aug 8 18:26:39 2008 From: rambert.marc at free.fr (Marc Rambert) Date: Fri, 8 Aug 2008 18:26:39 +0200 Subject: [Tutor] issue with the Backslash on IDLE 1.2.2 Message-ID: <E17CDCFB-F22D-46E6-8D2E-A3500FEDB868@free.fr> hi, I would like to make some regular expression, unfortunately I can't because the backslash doesn't work at all on IDLE 1.2.2 did someone already try this on a MacBook? The combination to do the backslash works properly (\ as you can see) but not in IDLE Doesn't someone notice already these ? thanks for you feedback Marc From gregor.lingl at aon.at Fri Aug 8 20:47:11 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 08 Aug 2008 20:47:11 +0200 Subject: [Tutor] Ongoing trouble with Turtle's end_fill() - caused by abug in turtle.py In-Reply-To: <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> References: <d71c7ed60808051549w10774cd2ub7f5225137b35ba7@mail.gmail.com> <1c2a2c590808060450u7b0909abpf9330785e498f0e2@mail.gmail.com> <489A3D2B.1020603@aon.at> <d71c7ed60808070954w43d7ca25h1d5f259d1e8f7d54@mail.gmail.com> <g7feoq$co0$1@ger.gmane.org> <d71c7ed60808071444i155f60d3m82d679e75d0569f@mail.gmail.com> Message-ID: <489C94AF.6080502@aon.at> Hi Dick, just to show you a bit of the versatility of the new turtle module I've prepared to tiny rectangle-generator program examples. They intentionally use different programming styles and also turtle graphics techniques different from the ones you used to accomplish something similar to what you did, of course in a very simplified way and without your eleborated user interface and colormanagement. ----------- Version 1: procedural, using stamp() ----------- from turtle import * from random import random, randint from time import sleep MAXLEN = 30 MAXWID = 25 def randomcolor(): return random(), random(), random() reset() title("Python turtle graphics: random rectangle generator") hideturtle() resizemode("user") shape("square") for cycle in range(randint(3, 5)): bgcolor(randomcolor()) for rect in range(randint(5,10)): shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID, randint(3, 10)) color(randomcolor(), randomcolor()) stamp() sleep(0.5) sleep(1) clearstamps() ----------- Version 2: object oriented, uses a list of turtles, which change their properties (size, color, visibility) ----------- from turtle import Screen, Turtle from random import random, randint from time import sleep MAXLEN = 30 MAXWID = 25 def randomcolor(): return random(), random(), random() class RectGenerator(object): def __init__(self): self.s = s = Screen() s.reset() s.title("Python turtle graphics: random rectangle generator") self.rectturtles = [] for n in range(10): t = Turtle(visible=False) t.hideturtle() t.resizemode("user") t.shape("square") self.rectturtles.append(t) def run(self): for cycle in range(randint(3, 5)): self.s.bgcolor(randomcolor()) n = randint(5,10) for index in range(n): t = self.rectturtles[index] t.shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID, randint(3, 10)) t.color(randomcolor(), randomcolor()) t.showturtle() sleep(0.5) sleep(1) for t in self.s.turtles(): t.hideturtle() if __name__ == "__main__": rg = RectGenerator() rg.run() Hope you like it Gregor From spython01 at gmail.com Fri Aug 8 21:07:03 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 15:07:03 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> Message-ID: <50a597410808081207u3df38830n25efd9b542135712@mail.gmail.com> > In general "from <module> import *" is a very bad idea. > > import <module> imports a module into its own namespace (e.g., to > access its functionality you would have to do "<module>.foo() and > <module>.bar()" The form that you chose to use imports all of a > module's contents into the current namespace. This means you can call > "foo()" and "bar()" directly, but it also means that if you have coded > a "foo()" and a "bar()" you will not have access to the functions in > the module you just imported. > Timothy, Thanks for the clarification. I had always wondered what the difference was. Samir From bgailer at gmail.com Fri Aug 8 23:12:04 2008 From: bgailer at gmail.com (bob gailer) Date: Fri, 08 Aug 2008 17:12:04 -0400 Subject: [Tutor] issue with the Backslash on IDLE 1.2.2 In-Reply-To: <E17CDCFB-F22D-46E6-8D2E-A3500FEDB868@free.fr> References: <E17CDCFB-F22D-46E6-8D2E-A3500FEDB868@free.fr> Message-ID: <489CB6A4.7090504@gmail.com> Marc Rambert wrote: > hi, > > I would like to make some regular expression, unfortunately I can't > because the backslash doesn't work Please explain "doesn't work". I interpret that as "I press the \ key and nothing shows up in the active window." -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From joefazee at gmail.com Fri Aug 8 23:22:50 2008 From: joefazee at gmail.com (A. Joseph) Date: Fri, 8 Aug 2008 14:22:50 -0700 Subject: [Tutor] I need a Python mentor Message-ID: <ea09b3700808081422r743473d4k35c76b2cb96617e2@mail.gmail.com> Hello everybody, i`m new to this list. I was programming in PHP before, of recent I started learning python. I need someone who can be giving me some assignment based on the chapter I read in the book, and the person will sometime review my code and tell me if it`s well structured. Thanks- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080808/05e4065a/attachment.htm> From flaxeater at gmail.com Fri Aug 8 23:36:45 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Fri, 8 Aug 2008 17:36:45 -0400 Subject: [Tutor] I need a Python mentor In-Reply-To: <ea09b3700808081422r743473d4k35c76b2cb96617e2@mail.gmail.com> References: <ea09b3700808081422r743473d4k35c76b2cb96617e2@mail.gmail.com> Message-ID: <584940990808081436r2164b0bem490ecc0b912de9da@mail.gmail.com> Actually the way this list works is there is no one person who will do this. However if you pose a specific question I'm sure you will get several helpful people will respond. Like this. What book did you read and what topics did it cover? From there someone perhaps even myself will be able to make up something nice for you to program. Then when you have problems with the program come back and ask questions. Since you already programmed in PHP I don't think you'll have too much trouble picking up python. On Fri, Aug 8, 2008 at 5:22 PM, A. Joseph <joefazee at gmail.com> wrote: > Hello everybody, i`m new to this list. I was programming in PHP before, of > recent I started learning python. I need someone who can be giving me some > assignment based on the chapter I read in the book, and the person will > sometime review my code and tell me if it`s well structured. > > Thanks- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From airchia at gmail.com Fri Aug 8 23:41:38 2008 From: airchia at gmail.com (Nick Scholtes) Date: Fri, 8 Aug 2008 16:41:38 -0500 Subject: [Tutor] I need a Python mentor In-Reply-To: <ea09b3700808081422r743473d4k35c76b2cb96617e2@mail.gmail.com> References: <ea09b3700808081422r743473d4k35c76b2cb96617e2@mail.gmail.com> Message-ID: <a2a149b80808081441i2266dedbkf1ee789e70c8395@mail.gmail.com> Hi, I'm a beginner in python, so I can't be a mentor, but here are some links that may help: http://uselesspython.com/ Python Wiki at: http://wiki.python.org/ Also google Think Python. It is a great resource. Nick On Fri, Aug 8, 2008 at 4:22 PM, A. Joseph <joefazee at gmail.com> wrote: > Hello everybody, i`m new to this list. I was programming in PHP before, of > recent I started learning python. I need someone who can be giving me some > assignment based on the chapter I read in the book, and the person will > sometime review my code and tell me if it`s well structured. > > Thanks- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Art: bellsoffreedom.cgsociety.org/gallery/ Blog: cognitivealchemy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080808/aaf07fbf/attachment.htm> From alan.gauld at btinternet.com Fri Aug 8 23:55:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Aug 2008 22:55:05 +0100 Subject: [Tutor] I need a Python mentor References: <ea09b3700808081422r743473d4k35c76b2cb96617e2@mail.gmail.com> Message-ID: <g7ifbt$4ff$1@ger.gmane.org> "A. Joseph" <joefazee at gmail.com> wrote > Hello everybody, i`m new to this list. I was programming in PHP > before, of > recent I started learning python. I need someone who can be giving > me some > assignment based on the chapter I read in the book, and the person > will > sometime review my code and tell me if it`s well structured. While some individual may volunteer its unlikely. The way the list works you pose questions and anyone on the list who knows (or thinks they do) the answer will reply. If you have code either post it in a mail(if short) or post a link to pastebin or some similar site. Hopefully some folks will have the time and intreest to review it. If you have studied a tyopic and want ideas on how to put it into practice just ask. Be as specific as possible. State where you are studying - tutorial, book, video etc. If you are getting errors post a short program that demonstrates the error plus all of the error text. You should get a reply pretty quickly. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Aug 8 23:59:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Aug 2008 22:59:51 +0100 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" forArrays References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com><1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com><50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com><e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> <50a597410808081207u3df38830n25efd9b542135712@mail.gmail.com> Message-ID: <g7ifkr$55b$1@ger.gmane.org> "S Python" <spython01 at gmail.com> wrote > Thanks for the clarification. I had always wondered what the > difference was. A useful tip is that if you have a long module name you can also use import module as shortname eg import numpy as n and then access numpy.foo() as n.foo() Sacves a lot of typing for a slight loss of clarity in maintenance - you have to remember which module the short names refer to! I tend to use full names in real code and use the abbreviated form when using the >>> prompt. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Aug 9 00:31:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Aug 2008 18:31:53 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> Message-ID: <1c2a2c590808081531n60692507ve2b3d0c6c0ea90e5@mail.gmail.com> On Fri, Aug 8, 2008 at 1:25 PM, Timothy Grant <timothy.grant at gmail.com> wrote: > In general "from <module> import *" is a very bad idea. > > import <module> imports a module into its own namespace (e.g., to > access its functionality you would have to do "<module>.foo() and > <module>.bar()" The form that you chose to use imports all of a > module's contents into the current namespace. This means you can call > "foo()" and "bar()" directly, but it also means that if you have coded > a "foo()" and a "bar()" you will not have access to the functions in > the module you just imported. Another reason not to use "from xx import *" is that it can make it very difficult to discover where a name is defined. If you have several "from xx import *" lines and then later you use a function "foo()" there is no easy way to tell which module foo came from. An alternative is to list just the names you want to import: from xx import foo Kent From spython01 at gmail.com Sat Aug 9 00:54:51 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 18:54:51 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" forArrays In-Reply-To: <g7ifkr$55b$1@ger.gmane.org> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> <50a597410808081207u3df38830n25efd9b542135712@mail.gmail.com> <g7ifkr$55b$1@ger.gmane.org> Message-ID: <50a597410808081554r777ce184j2d05d58ca43560a8@mail.gmail.com> > A useful tip is that if you have a long module name you can also use > > import module as shortname > > eg > > import numpy as n > > and then access numpy.foo() as > > n.foo() > > Sacves a lot of typing for a slight loss of clarity in > maintenance - you have to remember which module the > short names refer to! I tend to use full names in real code > and use the abbreviated form when using the >>> prompt. > Alan - Great suggestion! As I'm reading through the numpy documentation, there are a lot of great functions that I'd like to learn to use so your advice definitely helps. I was getting tired of constantly having to type "numpy.array" or "numpy.ones" all the time. Thanks again. Samir From spython01 at gmail.com Sat Aug 9 00:55:39 2008 From: spython01 at gmail.com (S Python) Date: Fri, 8 Aug 2008 18:55:39 -0400 Subject: [Tutor] Confused about "import Numeric" vs "import numpy" for Arrays In-Reply-To: <1c2a2c590808081531n60692507ve2b3d0c6c0ea90e5@mail.gmail.com> References: <50a597410808080856k7793b2f0q72fc63261957baf4@mail.gmail.com> <1c2a2c590808080925g5dd8f8bck902024df1601057f@mail.gmail.com> <50a597410808080929n6eeec54y5a14febdfbb1cdf7@mail.gmail.com> <e775286d0808081025j3e3dd753h959ae5087f3f210b@mail.gmail.com> <1c2a2c590808081531n60692507ve2b3d0c6c0ea90e5@mail.gmail.com> Message-ID: <50a597410808081555s7459e282k1ceb274d3f7a0fe1@mail.gmail.com> > Another reason not to use "from xx import *" is that it can make it > very difficult to discover where a name is defined. If you have > several "from xx import *" lines and then later you use a function > "foo()" there is no easy way to tell which module foo came from. > > An alternative is to list just the names you want to import: > from xx import foo > > Kent > Kent - Another great point. Thanks for contributing to the list. Samir From rdmoores at gmail.com Sat Aug 9 01:32:14 2008 From: rdmoores at gmail.com (Dick Moores) Date: Fri, 8 Aug 2008 16:32:14 -0700 Subject: [Tutor] To Tutor subscribers: should I send detailed questions about the Python 2.6b2's Turtle to the list? Message-ID: <d71c7ed60808081632w779f0f72mefe58da4ef1a35f@mail.gmail.com> The thread I started continues, and now concerns mainly the new Turtle module in Python 2.6b2. I am very interested in this, but I'm wondering is there are other 'kids" out there who are. Should I ask our resident expert, Gregor Lingl directly, or through the list? Opinions, please? Dick Moores, who is in his 2nd kidhood. From alan.gauld at btinternet.com Sat Aug 9 03:19:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Aug 2008 02:19:02 +0100 Subject: [Tutor] To Tutor subscribers: should I send detailed questionsabout the Python 2.6b2's Turtle to the list? References: <d71c7ed60808081632w779f0f72mefe58da4ef1a35f@mail.gmail.com> Message-ID: <g7iraa$tn9$1@ger.gmane.org> "Dick Moores" <rdmoores at gmail.com> wrote > The thread I started continues, and now concerns mainly the new > Turtle > module in Python 2.6b2. I am very interested in this, but I'm > wondering is there are other 'kids" out there who are. Should I ask > our resident expert, Gregor Lingl directly, or through the list? > > Opinions, please? Turtle is often used by beginners. Understanding the new modules foibles early seems a reasonable thread to pursue on this list. Lets just try to keep it in a single thread so that those who are not interested can filter it out and those searching in the future can find the full discourse. My view FWIW, Alan G From rdm at rcblue.com Sat Aug 9 12:12:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 09 Aug 2008 03:12:57 -0700 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 Message-ID: <20080809101310.2AE531E4002@bag.python.org> Gregor, <http://docs.python.org/dev/library/turtle.html#turtle.setup> 1. I want the window to open with the right edge 0 pixels from the right edge of my screen. However, setup(width=.75, height=.915, startx=-0, starty=0) doesn't work. I have to do the nearest thing, setup(width=.75, height=.915, startx=-1, starty=0). A small thing, but what's wrong with perfection. 2. There's a lot I don't understand in turtle.setup(width=_CFG[, "width"], height=_CFG[, "height"], startx=_CFG[, "leftright"], starty=_CFG[, "topbottom"]) What is '_CFG'? And how should anyone know what it is? What is "leftright"? And how to use it? What is "topbottom"? And how to use it? 3. http://docs.python.org/dev/library/turtle.html#turtle.stamp "turtle.stamp() Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling clearstamp(stamp_id)." But in your version 1 (<http://article.gmane.org/gmane.comp.python.tutor/49805>), the turtle is hidden by hideturtle()! What are you stamping? It seems the shape, or rectangle. If so, why does the doc say 'turtle'? 4. For my random_rectangles.py program I've started to try out the new turtle. (See the current state of random_rectanglesV16_web.py at <http://py77.python.pastebin.com/d3e842821>.) The only downside I've found is that the new turtle is much faster that the old. I want to set the speed so that the outlines of rectangles are drawn slowly enough that the user (me at present) can both appreciate the colors and have time to check the names of the colors being printed in the console window. Using the old turtle, I found that a default delay of 1 ((delay(1)) was just right; with the new turtle, setting a delay of even 50 affects only the first cycle of rectangles. So I don't use delay at all. Setting the slowest speed of 1 (speed(1)) is still too fast. How can I slow down the drawing of the rectangles? 5. I've been unable to figure out how to use onclick() (<http://docs.python.org/dev/library/turtle.html#turtle.onclick>). I'd like to find a way to pause my script by clicking on the screen -- so I could snag an image of what's showing, and then click again to restart the drawing of the rectangles. And in addition, being able to stop the program with a double click on the screen would be very handy. Could you explain how to do these, if in fact they are possible? That's all for now. Thanks, Dick From bgailer at gmail.com Sat Aug 9 17:02:33 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 09 Aug 2008 11:02:33 -0400 Subject: [Tutor] issue with the Backslash on IDLE 1.2.2 In-Reply-To: <530AA005-9130-4238-B212-D662E56DA7DD@free.fr> References: <E17CDCFB-F22D-46E6-8D2E-A3500FEDB868@free.fr> <489CB6A4.7090504@gmail.com> <530AA005-9130-4238-B212-D662E56DA7DD@free.fr> Message-ID: <489DB189.6080507@gmail.com> Please always reply to tutor at python.org as well as me. All of us can help and learn. Marc Rambert wrote: > >> Marc Rambert wrote: >>> hi, >>> >>> I would like to make some regular expression, unfortunately I can't >>> because the backslash doesn't work >> >> Please explain "doesn't work". >> >> I interpret that as "I press the \ key and nothing shows up in the >> active window." >> > hi yes you are right and this is when I am in french keyboard. I can't help here but perhaps someone else can. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From rdm at rcblue.com Sat Aug 9 17:08:35 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 09 Aug 2008 08:08:35 -0700 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <20080809101310.2AE531E4002@bag.python.org> References: <20080809101310.2AE531E4002@bag.python.org> Message-ID: <20080809151353.E03D81E4002@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/f7c823b4/attachment.htm> From noshius at gmail.com Sat Aug 9 17:55:43 2008 From: noshius at gmail.com (Joshua Nikkel) Date: Sat, 9 Aug 2008 11:55:43 -0400 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> References: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> Message-ID: <b55626e20808090855l714152e4mcbeb16f7336cf564@mail.gmail.com> I've pasted the following from my python shell. Please note that the first two lines of code are taken directly from the standard tutorial files under section 3.1.2. Will someone please tell me why something as basic and straightforward as this will not work? Everything else seems to work just fine, but not this. All I need is someway to get the length of a string... please help, nosh Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 ==== No Subprocess ==== >>> s = 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> len(s) TypeError: 'str' object is not callable >>> s 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> len(s) TypeError: 'str' object is not callable >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/334a5dd1/attachment.htm> From jtp at nc.rr.com Sat Aug 9 18:28:50 2008 From: jtp at nc.rr.com (James) Date: Sat, 9 Aug 2008 12:28:50 -0400 Subject: [Tutor] Unable to catch exception Message-ID: <e107b4ff0808090928m506a05dat2b9f62286732b8ab@mail.gmail.com> All, I'm having a rather strange problem that I'm hoping someone can shed some light on. I'm trying to catch a BadStatusLine exception raised by the httplib library. Below is the traceback that Python gives me when something goes wrong with one of my programs: ----- Traceback (most recent call last): File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner self.run() File "cherryTree.py", line 237, in run qDump = browser.open( url ).read() # get the new c3 queue File "/usr/lib/python2.5/site-packages/mechanize/_mechanize.py", line 203, in open return self._mech_open(url, data) File "/usr/lib/python2.5/site-packages/mechanize/_mechanize.py", line 229, in _mech_open response = UserAgentBase.open(self, request, data) File "/usr/lib/python2.5/site-packages/mechanize/_opener.py", line 181, in open response = urlopen(self, req, data) File "/usr/lib/python2.5/urllib2.py", line 399, in _open '_open', req) File "/usr/lib/python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/usr/lib/python2.5/site-packages/mechanize/_http.py", line 700, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.5/site-packages/mechanize/_http.py", line 675, in do_open r = h.getresponse() File "/usr/lib/python2.5/httplib.py", line 928, in getresponse response.begin() File "/usr/lib/python2.5/httplib.py", line 385, in begin version, status, reason = self._read_status() File "/usr/lib/python2.5/httplib.py", line 349, in _read_status raise BadStatusLine(line) BadStatusLine ----- This error happens when I try to open a page using mechanize. From what I gather this error only happens when the web server returns an unknown error. The error only happens once every blue moon, but to avoid a crash I setup a try/catch. try: <download page code here> catch BadStatusLine: print "yuck!" However, somehow the thread that this code is in still raised a BadStatusLine exception and the thread stopped cold. Thoughts on how to possibly fix this? Thanks! -j From mwalsh at mwalsh.org Sat Aug 9 21:59:00 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sat, 09 Aug 2008 14:59:00 -0500 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: <b55626e20808090855l714152e4mcbeb16f7336cf564@mail.gmail.com> References: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> <b55626e20808090855l714152e4mcbeb16f7336cf564@mail.gmail.com> Message-ID: <489DF704.8080905@mwalsh.org> Joshua Nikkel wrote: > IDLE 1.2.2 ==== No Subprocess ==== >>>> s = 'supercalifragilisticexpialidocious' >>>> len(s) > Traceback (most recent call last): > File "<pyshell#1>", line 1, in <module> > len(s) > TypeError: 'str' object is not callable My guess would be that you've reassigned the name 'len' to some other object, in this case a string. Does the error persist after you restart IDLE (or Restart Shell from the Shell menu)? HTH, Marty From dave6502 at googlemail.com Sun Aug 10 00:03:22 2008 From: dave6502 at googlemail.com (dave selby) Date: Sat, 9 Aug 2008 23:03:22 +0100 Subject: [Tutor] importing path question Message-ID: <f52017b60808091503g49082146h22625c32f574991d@mail.gmail.com> Hi all, I have a main directory 'kmotion2' where python scripts live. They access a library of scripts in 'kmotion2/core' as 'kmotion2/core' has a __init__.py file. However I now need to create a new directory 'utilities' inside 'kmotion2' that also needs to access scripts in 'core' kmotion2 directory | | core utilities So I need to import up the tree then back down. Is this possible ? Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From o.lenstra at gmail.com Sun Aug 10 02:24:52 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 02:24:52 +0200 Subject: [Tutor] Problems with Gauge Bar. Message-ID: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> Hello mail list ;) I've been developing a program for a while now (I am still a beginner though) and I want to add a progress bar (gauge bar) to my program. I am having quite some trouble actually implementing it though. I attached the file TSO.pyw which is my current project. I want to keep it within 1 python file if it's possible. Because I want to turn it into a single executable file. I am using wxPython for my GUI and a Win32API module. I hope to hear from you. Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/4e347602/attachment-0001.htm> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: TSO.pyw URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/4e347602/attachment-0001.txt> From queprime at gmail.com Sun Aug 10 06:57:27 2008 From: queprime at gmail.com (Que Prime) Date: Sat, 9 Aug 2008 21:57:27 -0700 Subject: [Tutor] IP address parse Message-ID: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> I'm trying to parse a log file for all ip addresses but can't get my RE to work. Thanks in advance for pointing me in the right direction #IP address parse ############################## import re infile = open("host0_declare.txt","r") outfile = open("out.txt","w") patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3}) for line in infile: m = patt.match(line) if m: outfile.write("%s.%s.%s.%s\n"%m.groups()) infile.close() outfile.close() ############################# -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/c36e7d44/attachment.htm> From timothy.grant at gmail.com Sun Aug 10 07:46:53 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sat, 9 Aug 2008 22:46:53 -0700 Subject: [Tutor] IP address parse In-Reply-To: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> References: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> Message-ID: <e775286d0808092246s2e3013a9y1cc409564d73ee91@mail.gmail.com> On Sat, Aug 9, 2008 at 9:57 PM, Que Prime <queprime at gmail.com> wrote: > I'm trying to parse a log file for all ip addresses but can't get my RE to > work. Thanks in advance for pointing me in the right direction > > > #IP address parse > > ############################## > import re > > infile = open("host0_declare.txt","r") > outfile = open("out.txt","w") > > patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3}) > > for line in infile: > m = patt.match(line) > if m: > outfile.write("%s.%s.%s.%s\n"%m.groups()) > > infile.close() > outfile.close() > ############################# > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Well there's one glaring problem, but I'll put that down to a re-keying error. there are no quote marks around your pattern string. However, the likely problem is that you are using re.match() instead of re.search(). Your re will ONLY match if the only thing on the line matches your pattern. -- Stand Fast, tjg. [Timothy Grant] From broek at cc.umanitoba.ca Sun Aug 10 07:38:18 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 10 Aug 2008 00:38:18 -0500 Subject: [Tutor] using generators to mock raw_input for doctest Message-ID: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> Hi all, I'm building a tool that will be run in a shell and depends heavily on raw_input. I'm also using doctest (mostly via doctest.testfile) to create unit tests for it. After thinking a while about how to use doctest for invocations of raw_input, I came up with the general sort of idea shown in the toy code below. I have two questions: 1) As I've never really made generators `mine,' I'm not sure if this is the best (read `best' as `easiest and simplest') way to use a generator for this task. Should I be doing it differently? 2) Is there some better way to enable doctesting of code that uses raw_input? All I found when googling was the suggestion that in place of: def myfunc(): # code employing raw_input here one could write: def myfunc(input_meth=raw_input): # code with raw_input calls replaced with input_meth calls but that seems like complicating my code for the non-doctest case. Perhaps that worries me too much, though---I've yet to become test infected ;-) Thanks for any input, Brian vdB import sys class myraw(object): def __init__(self, values): self.values = values self.stream = self.mygen() def mygen(self): for i in self.values: yield i def readline(self): return str(self.stream.next()) def double_user_input(): """A silly example to illustrate my method for testing. >>> sys.stdin = myraw([1,21,12.5,3.1415]) >>> double_user_input() 2 >>> double_user_input() 42 >>> double_user_input() 25 >>> double_user_input() # doctest: +ELLIPSIS 6.28300... >>> sys.stdin = sys.__stdin__ """ val = float(raw_input()) * 2 val = [val, int(val)][val == int(val)] return val def __test(): import doctest doctest.testmod() if __name__ == "__main__": __test() From rosenville at gmail.com Sun Aug 10 07:58:53 2008 From: rosenville at gmail.com (Josh Rosen) Date: Sat, 9 Aug 2008 22:58:53 -0700 Subject: [Tutor] IP address parse In-Reply-To: <1B02D548-2814-4259-9A5F-3224E1C2E0F6@gmail.com> References: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> <1B02D548-2814-4259-9A5F-3224E1C2E0F6@gmail.com> Message-ID: <418CDC50-66EC-47EC-BFC1-CF825A75ED12@gmail.com> On Aug 9, 2008, at 10:46 PM, Josh Rosen wrote: > There are a few different problems in your code. First off, regular > expressions must be passed to re.compile() as strings. > >> patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\. >> (\[0-9]{1,3}) > > should read > > patt = re.compile(r"(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\. > (\[0-9]{1,3})"). > > I've used a raw string literal here to prevent Python from > interpreting the backslashes as character escapes. However, this > regular expression still won't work. If you're going to use a > character class, there's no need to put a backslash in front of it. > Correcting this, the line becomes: > > patt = re.compile(r"([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9] > {1,3})") > > This works, but it can be made simpler by using the shorthand > notation \d in place of [0-9]: > > patt = re.compile(r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})") > > Since it doesn't look like you're doing anything with the parts of > the ip besides writing the whole ip to a file, you can eliminate the > capturing parentheses in your regular expression and replace them > with a single pair: > > patt = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") > > The string formatting expression becomes: > > outfile.write("%s\n" % m.groups()) > > Hope this helps, > Josh > > > On Aug 9, 2008, at 9:57 PM, Que Prime wrote: > >> I'm trying to parse a log file for all ip addresses but can't get >> my RE to work. Thanks in advance for pointing me in the right >> direction >> >> >> #IP address parse >> >> ############################## >> import re >> >> infile = open("host0_declare.txt","r") >> outfile = open("out.txt","w") >> >> patt = re.compile(\[0-9]{1,3})\.(\[0-9]{1,3})\.(\[0-9]{1,3})\. >> (\[0-9]{1,3}) >> >> for line in infile: >> m = patt.match(line) >> if m: >> outfile.write("%s.%s.%s.%s\n"%m.groups()) >> >> infile.close() >> outfile.close() >> ############################# >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > From gregor.lingl at aon.at Sun Aug 10 08:59:38 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sun, 10 Aug 2008 08:59:38 +0200 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <20080809151353.E03D81E4002@bag.python.org> References: <20080809101310.2AE531E4002@bag.python.org> <20080809151353.E03D81E4002@bag.python.org> Message-ID: <489E91DA.8070001@aon.at> Dick Moores schrieb: > At 03:12 AM 8/9/2008, Dick Moores wrote: >> 4. For my random_rectangles.py program I've started to try out the >> new turtle. (See the current state of random_rectanglesV16_web.py at >> < http://py77.python.pastebin.com/d3e842821>.) >> <http://py77.python.pastebin.com/d3e842821%3E.%29%A0> The only >> downside I've found is that the new turtle is much faster that the >> old. I want to set the speed so that the outlines of rectangles are >> drawn slowly enough that the user (me at present) can both appreciate >> the colors and have time to check the names of the colors being >> printed in the console window. Using the old turtle, I found that a >> default delay of 1 ((delay(1)) was just right; with the new turtle, >> setting a delay of even 50 affects only the first cycle of >> rectangles. So I don't use delay at all. Setting the slowest speed of >> 1 (speed(1)) is still too fast. How can I slow down the drawing of >> the rectangles? > > I seem to have solved #4. > > I had been using tracer() as tracer(True) in my function draw_rect(). > In rereading the doc, I noticed that < > http://docs.python.org/dev/library/turtle.html#turtle.tracer> > has > "turtle.tracer(/flag=None/, /delay=None/)" > > so in draw_rect() I tried changing tracer(True) to tracer(True, dly). > (See the new version, random_rectanglesV17_web.py, at < > http://py77.python.pastebin.com/f54c9211f>, lines 220, 230, 240, etc.) > > Then I enabled the user to enter both speed and delay, with a default > speed of 1 and a default delay of 15 (see the new function > get_speed_and_delay_from_user(), lines 153-179). On my computer, these > defaults seemed to be ideal. > That's fine! > But now I have another puzzle: As long as delay is kept constant, it > doesn't seem to matter what speed is chosen -- from the slowest of 1 > to the fastest of 0. Why is speed irrelevant? Did you observe that faster speeds need arguments in the range from 2 to 10? That means speed(10) is fastest speed. Gregor > > Dick > > BTW at < http://py77.python.pastebin.com/f54c9211f>, if you click on > the 'view diff' link just above the code, you'll get a diff with the > immediately previous version. > > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sun Aug 10 10:15:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 09:15:39 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> Message-ID: <g7m83h$b2k$1@ger.gmane.org> "Olrik Lenstra" <o.lenstra at gmail.com> wrote > I've been developing a program for a while now (I am still a > beginner > though) and I want to add a progress bar (gauge bar) to my program. > I am having quite some trouble actually implementing it though. I > attached > the file TSO.pyw which is my current project. Can you show us what you have tried so far? > I want to keep it within 1 python file if it's possible. Because I > want to > turn it into a single executable file. You can use multiple files and still produce an EXE using py2exe or similar. There is no need to keep it in one file. Alan G From o.lenstra at gmail.com Sun Aug 10 12:49:04 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 12:49:04 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <g7m83h$b2k$1@ger.gmane.org> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <g7m83h$b2k$1@ger.gmane.org> Message-ID: <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> This is the part I tried to get the Bar in. I actually got it in GUI wise. But I had no idea to let it run the moment I clicked "Scan" I got the code I tried to put in from another python file that I found somewhere on the net. It's attached as test.pyw <<< class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(300, 280), style = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)) self.timer = wx.Timer(self, 1) self.count = 0 panel = wx.Panel(self, -1) introFont = wx.Font(10, wx.ROMAN, wx.NORMAL, wx.NORMAL) introText = wx.StaticText(panel, -1, introRaw,(50, 10), style=wx.ALIGN_CENTRE) introText.SetFont(introFont) wx.Button(panel, 1, 'Scan!', (115, 90)) wx.Button(panel, 2, 'Logs', (115, 120)) wx.Button(panel, 3, 'Version', (115, 150)) wx.Button(panel, 4, 'Credits', (115, 180)) wx.Gauge(panel, 5, 50, (50, 210), size=(250, 25)) self.Bind(wx.EVT_BUTTON, self.OnScan, id=1) self.Bind(wx.EVT_BUTTON, self.OnLogs, id=2) self.Bind(wx.EVT_BUTTON, self.OnVersion, id=3) self.Bind(wx.EVT_BUTTON, self.OnCredits, id=4) >>> Alan, I'm using pyinstaller. is it possible to make several python files into a single exe? If so, Can you direct me to maybe some documentation? (I might have overlooked it.) The program runs fine and works perfectly as the code is right now, But while I'm asking for the bar, can I ask for some advice on the following bit of code too? <<< ##------------------------------------------------------------------------------ ## Define all the private IP ranges that we're not going to filter in ## the ipconfig part of the program. ## From private4 to private19 is actually 1 range. (Needs to be looked at.) ##------------------------------------------------------------------------------ private1 = r"192\.168\.\d+\.\d+" private2 = r"169\.254\.\d+\.\d+" private3 = r"10\.\d+\.\d+\.\d+" private4 = r"172\.16\.\d+\.\d+" private5 = r"172\.17\.\d+\.\d+" private6 = r"172\.18\.\d+\.\d+" private7 = r"172\.19\.\d+\.\d+" private8 = r"172\.20\.\d+\.\d+" private9 = r"172\.21\.\d+\.\d+" private10 = r"172\.22\.\d+\.\d+" private11 = r"172\.23\.\d+\.\d+" private12 = r"172\.24\.\d+\.\d+" private13 = r"172\.25\.\d+\.\d+" private14 = r"172\.26\.\d+\.\d+" private15 = r"172\.27\.\d+\.\d+" private16 = r"172\.28\.\d+\.\d+" private17 = r"172\.29\.\d+\.\d+" private18 = r"172\.30\.\d+\.\d+" private19 = r"172\.31\.\d+\.\d+" ##------------------------------------------------------------------------------ ## Define concealip. This will make sure no public addresses will be published ## on the forums and decreasing the risk for the poster. ##------------------------------------------------------------------------------ def concealip(): ##------------------------------------------------------------------------------ ## Start a loop to replace the public addresses with X's. ## Currently this part is really inefficient. ##------------------------------------------------------------------------------ lines = file('ipconfig.txt', "r+").readlines() for i in range(len(lines)): if re.search("IP\D+ \:", lines[i]): if not re.search(private1, lines[i]): if not re.search(private2, lines[i]): if not re.search(private3, lines[i]): if not re.search(private4, lines[i]): if not re.search(private5, lines[i]): if not re.search(private6, lines[i]): if not re.search(private7, lines[i]): if not re.search(private8, lines[i]): if not re.search(private9, lines[i]): if not re.search(private10, lines[i]): if not re.search(private11, lines[i]): if not re.search(private12, lines[i]): if not re.search(private13, lines[i]): if not re.search(private14, lines[i]): if not re.search(private15, lines[i]): if not re.search(private16, lines[i]): if not re.search(private17, lines[i]): if not re.search(private18, lines[i]): if not re.search(private19, lines[i]): lines[i] = lines[i].replace('1', 'x') lines[i] = lines[i].replace('2', 'x') lines[i] = lines[i].replace('3', 'x') lines[i] = lines[i].replace('4', 'x') lines[i] = lines[i].replace('5', 'x') lines[i] = lines[i].replace('6', 'x') lines[i] = lines[i].replace('7', 'x') lines[i] = lines[i].replace('8', 'x') lines[i] = lines[i].replace('9', 'x') lines[i] = lines[i].replace('0', 'x') >>> This bit of code is meant to X-away public IP addresses on an ipconfig log. It works perfectly but I think it's way to large or ineffective. Since I'm only a beginner I left it at this for now, Is there a way for me to improve this? Thanks for all the help!! Regards, Olrik 2008/8/10 Alan Gauld <alan.gauld at btinternet.com> > > "Olrik Lenstra" <o.lenstra at gmail.com> wrote > > I've been developing a program for a while now (I am still a beginner >> though) and I want to add a progress bar (gauge bar) to my program. >> I am having quite some trouble actually implementing it though. I attached >> the file TSO.pyw which is my current project. >> > > Can you show us what you have tried so far? > > I want to keep it within 1 python file if it's possible. Because I want to >> turn it into a single executable file. >> > > You can use multiple files and still produce an EXE using > py2exe or similar. There is no need to keep it in one file. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/d95568e9/attachment.htm> From alan.gauld at btinternet.com Sun Aug 10 15:51:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 14:51:32 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com><g7m83h$b2k$1@ger.gmane.org> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> Message-ID: <g7mrp9$mm0$1@ger.gmane.org> "Olrik Lenstra" <o.lenstra at gmail.com> wrote > This is the part I tried to get the Bar in. I actually got it in GUI > wise. > But I had no idea to let it run the moment I clicked "Scan" OK, Normally you have to update the bar values from inside a loop on your Scan method. In practice you probably need to use a timer to relinquish control back to the GUI so that the Guage refreshes itself. In pseudo code: def onScan(self): self.myfile = open('foo.txt') self.count = 0 self.setTimer(0.01, self.processLine) def processLine(self) line = self.myfile.readline() if line: processLine(line) self.count += 1 self.myGauge.setValue(count) self.setTimer(0.01, self.processLine) else: self.myGuage.setValue(0) This also allows the user to use the GUI while the scan is running > Alan, I'm using pyinstaller. is it possible to make several python > files > into a single exe? Yes, it must be since every time you import a module you are using another file. Its quite hard to write any useful application in Python without importing at least one module. Your files are no different to the standard modules like os, sys, time, etc... > If so, Can you direct me to maybe some documentation? (I > might have overlooked it.) Sorry, I've never used pyinstaller but if it can't do this it isn't of much use! > while I'm asking for the bar, can I ask for some advice on the > following bit > of code too? Of course! :-) > ## Define all the private IP ranges that we're not going to filter > in > ## the ipconfig part of the program. > ## From private4 to private19 is actually 1 range. (Needs to be > looked at.) > ##------------------------------------------------------------------------------ > private1 = r"192\.168\.\d+\.\d+" > private2 = r"169\.254\.\d+\.\d+" > private3 = r"10\.\d+\.\d+\.\d+" > ... > private19 = r"172\.31\.\d+\.\d+" Why not put them in a list or tuple called privates? It will save typing and: > lines = file('ipconfig.txt', "r+").readlines() > for i in range(len(lines)): > if re.search("IP\D+ \:", lines[i]): > if not re.search(private1, lines[i]): > if not re.search(private2, lines[i]): > .... > if not re.search(private19, lines[i]): The if not search lines could then be replaced by a loop. This has the added advantage that you can change the list of privates(adding or deleting entries)) without changing this code. lines = file('ipconfig.txt', "r+").readlines() for i in range(len(lines)): if re.search("IP\D+ \:", lines[i]): for p in patterns: if search(p,lines[i]): break else: # equivalent of the end of your chain Another approach would be to compbine all the private IP addresses into a single long regex. You can then do a single search for the pattern. This would be faster but slightly harder to read/debug. Choosing the right data structure is half the battle in writing clean code. If you find yourself writing code that is obviously cumbersome go back and think about whether you can design a better data struvcture. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From o.lenstra at gmail.com Sun Aug 10 16:21:16 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 16:21:16 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <g7mrp9$mm0$1@ger.gmane.org> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <g7m83h$b2k$1@ger.gmane.org> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <g7mrp9$mm0$1@ger.gmane.org> Message-ID: <3c8f6fd70808100721w30cb9ee1of289c478e716dc7d@mail.gmail.com> I'm probably asking for a lot here. But I don't think I understand this fully. This is the part I tried to get the Bar in. I actually got it in GUI wise. >> But I had no idea to let it run the moment I clicked "Scan" >> > > OK, Normally you have to update the bar values from inside a > loop on your Scan method. In practice you probably need to > use a timer to relinquish control back to the GUI so that the > Guage refreshes itself. In pseudo code: > def onScan(self): > self.myfile = open('foo.txt') > self.count = 0 > self.setTimer(0.01, self.processLine) > > def processLine(self) > line = self.myfile.readline() > if line: > processLine(line) > self.count += 1 > self.myGauge.setValue(count) > self.setTimer(0.01, self.processLine) > else: > self.myGuage.setValue(0) > > This also allows the user to use the GUI while the scan is running > Ok. So lets see if I got this right. In the onScan you define self.myfile to open 'foo.txt' One thing I don't get here is what is foo.txt used for? Then you set the count to 0 Then you set the timer to 0.01 with the event processLine? then in the processLine you add 1 to the count with every line that is read? ## Define all the private IP ranges that we're not going to filter in >> ## the ipconfig part of the program. >> ## From private4 to private19 is actually 1 range. (Needs to be looked >> at.) >> >> ##------------------------------------------------------------------------------ >> private1 = r"192\.168\.\d+\.\d+" >> private2 = r"169\.254\.\d+\.\d+" >> private3 = r"10\.\d+\.\d+\.\d+" >> ... >> private19 = r"172\.31\.\d+\.\d+" >> > > Why not put them in a list or tuple called privates? > It will save typing and: > > lines = file('ipconfig.txt', "r+").readlines() >> for i in range(len(lines)): >> if re.search("IP\D+ \:", lines[i]): >> if not re.search(private1, lines[i]): >> if not re.search(private2, lines[i]): >> .... >> if not re.search(private19, lines[i]): >> > > The if not search lines could then be replaced by a loop. > This has the added advantage that you can change the > list of privates(adding or deleting entries)) without > changing this code. > > lines = file('ipconfig.txt', "r+").readlines() > for i in range(len(lines)): > if re.search("IP\D+ \:", lines[i]): > for p in patterns: > if search(p,lines[i]): > break > else: > # equivalent of the end of your chain > > Another approach would be to compbine all the private IP > addresses into a single long regex. You can then do a > single search for the pattern. This would be faster but > slightly harder to read/debug. > I'll try to implement that loop :) Thanks for the help! Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/95e50682/attachment.htm> From greg at thewhittiers.com Sun Aug 10 16:26:35 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 10 Aug 2008 10:26:35 -0400 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <g7m83h$b2k$1@ger.gmane.org> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> Message-ID: <a250eacf0808100726i57199174p7a2c7040f3b46f10@mail.gmail.com> On Sun, Aug 10, 2008 at 6:49 AM, Olrik Lenstra <o.lenstra at gmail.com> wrote: > The program runs fine and works perfectly as the code is right now, But > while I'm asking for the bar, can I ask for some advice on the following bit > of code too? > > <<< > ##------------------------------------------------------------------------------ > ## Define all the private IP ranges that we're not going to filter in > ## the ipconfig part of the program. > ## From private4 to private19 is actually 1 range. (Needs to be looked at.) > ##------------------------------------------------------------------------------ > private1 = r"192\.168\.\d+\.\d+" > private2 = r"169\.254\.\d+\.\d+" > private3 = r"10\.\d+\.\d+\.\d+" > private4 = r"172\.16\.\d+\.\d+" > private5 = r"172\.17\.\d+\.\d+" > private6 = r"172\.18\.\d+\.\d+" > private7 = r"172\.19\.\d+\.\d+" > private8 = r"172\.20\.\d+\.\d+" > private9 = r"172\.21\.\d+\.\d+" > private10 = r"172\.22\.\d+\.\d+" > private11 = r"172\.23\.\d+\.\d+" > private12 = r"172\.24\.\d+\.\d+" > private13 = r"172\.25\.\d+\.\d+" > private14 = r"172\.26\.\d+\.\d+" > private15 = r"172\.27\.\d+\.\d+" > private16 = r"172\.28\.\d+\.\d+" > private17 = r"172\.29\.\d+\.\d+" > private18 = r"172\.30\.\d+\.\d+" > private19 = r"172\.31\.\d+\.\d+" > How about r = re.compile(r"(\d+)\.(\d+)\.\d+\.\d+") m = re.search(line[i]) if m: n1, n2 = map(int,m.groups()) # n1, n2 now have the first two numbers of the IP address Once you have n1, n2, you can check what range the ip is in and act accordingly. Greg From rdm at rcblue.com Sun Aug 10 16:28:33 2008 From: rdm at rcblue.com (Dick Moores) Date: Sun, 10 Aug 2008 07:28:33 -0700 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <489E913D.60507@aon.at> References: <20080809101310.2AE531E4002@bag.python.org> <489E913D.60507@aon.at> Message-ID: <20080810142948.CB5711E4003@bag.python.org> At 11:57 PM 8/9/2008, you wrote: >Dick Moores schrieb: >>Gregor, >> >><http://docs.python.org/dev/library/turtle.html#turtle.setup> >>1. I want the window to open with the right edge 0 pixels from the >>right edge of my screen. >>However, setup(width=.75, height=.915, startx=-0, starty=0) doesn't >>work. I have to do the nearest thing, >>setup(width=.75, height=.915, startx=-1, starty=0). A small thing, >>but what's wrong with perfection. >Hi Dick, >a good observation, but I think this cannot be changed, because of > > >>> -0 == 0 >True OK. I just thought there might be a workaround. Or should be. >in Python >>2. There's a lot I don't understand in >>turtle.setup(width=_CFG[, "width"], height=_CFG[, "height"], >>startx=_CFG[, "leftright"], starty=_CFG[, "topbottom"]) >> >>What is '_CFG'? And how should anyone know what it is? >>What is "leftright"? And how to use it? >>What is "topbottom"? And how to use it? >_CFG is an internal dictionary, which contains configuration data. >You can change these >by editing adding or editing the turtle.cfg file (an example is in >the Demo directory). >How to do this you can find here: > >http://docs.python.org/dev/library/turtle.html#how-to-configure-screen-and-turtles > I suppose you'll add a mention of '_CFG' to that? >>3. http://docs.python.org/dev/library/turtle.html#turtle.stamp >> >>"turtle.stamp() >>Stamp a copy of the turtle shape onto the canvas at the current >>turtle position. Return a stamp_id for that stamp, which can be >>used to delete it by calling clearstamp(stamp_id)." >> >>But in your version 1 >>(<http://article.gmane.org/gmane.comp.python.tutor/49805>), the >>turtle is hidden by hideturtle()! What are you stamping? It seems >>the shape, or rectangle. If so, why does the doc say 'turtle'? >there will be stamped the shape of the turtle, that appeared if it >were not hidden. But what get's 'stamped' is not only the turtle, is it. That's what is confusing, IMO. And would it not be a good idea to define 'stamp'? >General remark: you can investigate Python and especially its turtle >module interactively >using IDLE. But note: in the case of graphics (Tkinter and >especially turtle.py) you have to >use the -n switch of IDLE. So the link calling idle must look >something like this: > >/... ../... ../python /... ../.../.../idle.pyw -n > >the dotted parts representig the path according to your system configuration > >If you have done this onceyou can issue function calls on after another and >observe what happens. E. g.: > > >>> from turtle import * > >>> reset() > >>> shape("square") > >>> color("blue", "red") > >>> resizemode("user") # at first no visual effect, but ... > >>> turtlesize(2,3,5) > >>> fd(100) > >>> left(45) > >>> pensize(8) > >>> fd(100) > >>> left(90) > >>> pencolor("green") > >>> fd(100) > >>> turtlesize(1,5) > >>> left(1080) > >>> stamp() >8 > >>> left(45) > >>> ht() > >>> fd(100) > >>> stamp() >9 > >>> left(45) > >>> fd(100) > >>> stamp() >10 > >>> > >... and so on. >If you want to know how some function works and the docs >don't give you a proper clue, simply try out. Ah. Very good. After doing that I understand a lot more now. However, it was of no help with "leftright" or "topbottom" of my question #2. >>4. For my random_rectangles.py program I've started to try out the >>new turtle. (See the current state of random_rectanglesV16_web.py >>at <http://py77.python.pastebin.com/d3e842821>.) The only downside >>I've found is that the new turtle is much faster that the old. I >>want to set the speed so that the outlines of rectangles are drawn >>slowly enough that the user (me at present) can both appreciate the >>colors and have time to check the names of the colors being printed >>in the console window. Using the old turtle, I found that a default >>delay of 1 ((delay(1)) was just right; with the new turtle, setting >>a delay of even 50 affects only the first cycle of rectangles. So I >>don't use delay at all. Setting the slowest speed of 1 (speed(1)) >>is still too fast. How can I slow down the drawing of the rectangles? >I suppose you have some call of reset() or clear() which resets the >delay. So try a >delay call at the beginning of every cycle. You're right! The clear() between cycles was doing that. So now I have speed(spd) at the top of draw_rect(). And now I find that speed(4) and delay(15) work the best for what I want. So those are now the defaults. BTW the latest version is <http://py77.python.pastebin.com/pastebin.php?diff=f159f133d>. Now the user can accept all the defaults at once. (See the prompt for this, line 427. Also, the dimensions of the window and of the rectangles are now proportional to the size and resolution of the user's monitor. See new function adjust_for_monitor_size_and_resolution(), line 196, and revised function get_next_rect_params(), lines 207-209. >>5. I've been unable to figure out how to use onclick() >>(<http://docs.python.org/dev/library/turtle.html#turtle.onclick>). >>I'd like to find a way to pause my script by clicking on the screen >>-- so I could snag an image of what's showing, and then click again >>to restart the drawing of the rectangles. And in addition, being >>able to stop the program with a double click on the screen would be >>very handy. Could you explain how to do these, if in fact they are possible? >This idea for an event driven program affords a bit of different >thinking and a different >program structure. I'll come up with a proposition and an explanation of some >prerequisites in another posting. (I have not got the time to do >that now). Great! Thank you. Dick From o.lenstra at gmail.com Sun Aug 10 16:38:26 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sun, 10 Aug 2008 16:38:26 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <a250eacf0808100726i57199174p7a2c7040f3b46f10@mail.gmail.com> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <g7m83h$b2k$1@ger.gmane.org> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <a250eacf0808100726i57199174p7a2c7040f3b46f10@mail.gmail.com> Message-ID: <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> That bit of code doesn't make a lot of sense to me so far. I don't see how that could "X" out a public address. (I do appreciate the help!) Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/eef059bf/attachment.htm> From greg at thewhittiers.com Sun Aug 10 17:41:23 2008 From: greg at thewhittiers.com (greg whittier) Date: Sun, 10 Aug 2008 11:41:23 -0400 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <g7m83h$b2k$1@ger.gmane.org> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <a250eacf0808100726i57199174p7a2c7040f3b46f10@mail.gmail.com> <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> Message-ID: <a250eacf0808100841r32f44438nfe5ac749177658ac@mail.gmail.com> On Sun, Aug 10, 2008 at 10:38 AM, Olrik Lenstra <o.lenstra at gmail.com> wrote: > That bit of code doesn't make a lot of sense to me so far. > I don't see how that could "X" out a public address. > > (I do appreciate the help!) > > Regards, > Olrik > r = re.compile(r"(\d+)\.(\d+)\.\d+\.\d+") m = re.search(lines[i]) # search returns a match object if m: # the match object will be "None" if there is no match n1, n2 = m.groups() # n1, and n2 contain the strings corresponding to the parts # of the regexp in parentheses above # e.g., n1 == '192' and n2 == '168' n1 = int(n1) n2 = int(n2) # convert them to integers (I used the "map" trick before to do this in one line) # n1, n2 now have the first two numbers of the IP address # Once you have n1, n2, you can check what range the ip is in and act accordingly. # I left this out before, but here's how you might do the check if ( n1 == 10 or (n1 == 192 and n2 == 168) or (n1 == 169 and n2 == 254) or (n1 == 172 and n2 >= 16 and n2 <= 31)): lines[i] = r.sub("xxx.xxx.xxx.xxx",lines[i]) # using sub is a little more compact Check out the python regular expression howto - http://www.amk.ca/python/howto/regex/ Greg From xboxmuncher at gmail.com Sun Aug 10 18:28:16 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 10 Aug 2008 12:28:16 -0400 Subject: [Tutor] Back-end Bittorrent Client in python Message-ID: <df531c470808100928m7465cf0cr5c85b4793bb3e4cf@mail.gmail.com> I want to be able to download bittorrent files with the bittorrent protocol in my python program using only the native libraries in it. All I am interested is being able to download & upload simultanaeously, reading parts that make up the torrent package and being able to choose files/folders to download, when uploading being able to point to other directories and locations where the files reside. (not necessarily in the same hierarchy/architecture of the original torrent package) I don't quite know what to call this behavior that I'm wanting. I would call it a bittorrent class that I can use to download and control the protocol within my python program... A shell? A back-end bittorrent client.. I'd appreciate some pointers on where to get started implementing something like this, and how I can take advantage of a lot of other BT clients that already exist in python. IE: I've read about official BT client, bitornado, ABC client, etc.. but they all seem to be stand-alone clients for users interesting in downloading the torrent packages. I want something that I can implement and manipulate within my own program. -thanks for your time -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/76dcc59d/attachment.htm> From alan.gauld at btinternet.com Sun Aug 10 19:23:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 18:23:22 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com><g7m83h$b2k$1@ger.gmane.org><3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com><g7mrp9$mm0$1@ger.gmane.org> <3c8f6fd70808100721w30cb9ee1of289c478e716dc7d@mail.gmail.com> Message-ID: <g7n86f$nfa$1@ger.gmane.org> "Olrik Lenstra" <o.lenstra at gmail.com> wrote > I'm probably asking for a lot here. But I don't think I understand > this > fully. Thats OK. >> def onScan(self): >> self.myfile = open('foo.txt') >> self.count = 0 >> self.setTimer(0.01, self.processLine) >> >> def processLine(self) >> line = self.myfile.readline() >> if line: >> processLine(line) >> self.count += 1 >> self.myGauge.setValue(count) >> self.setTimer(0.01, self.processLine) >> else: >> self.myGuage.setValue(0) > Ok. So lets see if I got this right. In the onScan you define > self.myfile to > open 'foo.txt' One thing I don't get here is what is foo.txt used > for? Its the file that you want to scan - assuming there is a file. It could be a list or anything else - I don't actually know from your code what onScan is supposed to do! :-) > Then you set the count to 0 > Then you set the timer to 0.01 with the event processLine? Thats right. The idea is to set up a timer to fire after 1/100 of a second. Then in processLine set up another one after processing each line until the file (or list etc) is scanned. > then in the processLine you add 1 to the count with every line that > is read? Yes and set the Guage value to whatever count is. Then next time the GUI draws itself the new cvalue will appear in the guage. The important bit is that: 1) We use onScan to initialise things not to actually do the processing 2) We create the timer each time we process some data (you could opt to process more than one line - say batches of 10, but the important point is that its only ever a short period of processing. 3) We update the count and then the guage after each batch completes HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From nosh3141 at gmail.com Sat Aug 9 17:45:04 2008 From: nosh3141 at gmail.com (Joshua Nikkel) Date: Sat, 9 Aug 2008 11:45:04 -0400 Subject: [Tutor] something is fundamentally wrong... Message-ID: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> I've pasted the following from my python shell. Please note that the first two lines of code are taken directly from the standard tutorial files under section 3.1.2. Will someone please tell me why something as basic and straightforward as this will not work? Everything else seems to work just fine, but not this. All I need is someway to get the length of a string... please help, nosh Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 ==== No Subprocess ==== >>> s = 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> len(s) TypeError: 'str' object is not callable >>> s 'supercalifragilisticexpialidocious' >>> len(s) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> len(s) TypeError: 'str' object is not callable >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/6c2a9d46/attachment-0001.htm> From federo at email.si Sat Aug 9 17:57:14 2008 From: federo at email.si (Federo) Date: Sat, 09 Aug 2008 17:57:14 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> <20080808091219.22A228B9F2@www1.email.si> <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> Message-ID: <20080809155715.F0E698FFFC@www1.email.si> Kent hi I do hope we are now close to the final solution. I have used Firefox plagin TamperData as you suggested and concequently amanded the code. Header Fields are know clear (you can see them in the attached file). There is some problem with Python code: import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet555', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() f.close() #print(data) #params2 = dict(contentProvider='pinnacor', quoteSymbol='goog', optionChain='goog', countryCode='US', optionRange='NTM', tickerSymbol='goog', ContentType='stockQuote') params2['contentProvider'] = 'pinnacor' params2['quoteSymbol'] = 'goog' params2['optionChain'] = 'goog' params2['countryCode'] = 'US' params2['optionRange'] = 'NTM' params2['tickerSymbol'] = 'goog' params2['contentType'] = 'stockQuote' params2['quote.x'] = 'submitted' f = opener.open('https://investor.firstrade.com/firstrade/mainmenu.do', params2) data2 = f.read() f.close() print(data2) Error Message: File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1115, in https_open return self.do_open(httplib.HTTPSConnection, req) File "C:\Python25\lib\urllib2.py", line 1079, in do_open h.request(req.get_method(), req.get_selector(), req.data, headers) File "C:\Python25\lib\httplib.py", line 866, in request self._send_request(method, url, body, headers) File "C:\Python25\lib\httplib.py", line 892, in _send_request self.send(body) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "C:\Python25\lib\httplib.py", line 1108, in send return self._ssl.write(stuff) TypeError: write() argument 1 must be string or read-only buffer, not dict Cheers, Fedo On Fri, 8 Aug 2008 at 13:56:29, Kent Johnson wrote: > On Fri, Aug 8, 2008 at 5:12 AM, Federo <federo at email.si> wrote: > > Kent hi > > > > I am still unable to enter data into textbox and getting back server reply. > The > > main problem is that I do not understand which fileds / header to observer > > using Firefox Fireburg. Atteched you can see headers I went through. With > red > > font I marked differences among stages. In nider of the headers I didn't > find > > fieldds you included in your workable login code. > > Hi Federo, > > This isn't really a Python question anymore, it is a matter of > figuring out what the server requires. You have to look at the form > data as well as the headers. TamperData is one Firefox pluging that > can do that, I'm sure there are others as well. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_VPR.doc Type: application/octet-stream Size: 146944 bytes Desc: FormManagement_VPR.doc URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/fe3e705b/attachment-0001.obj> From federo at email.si Sat Aug 9 21:48:41 2008 From: federo at email.si (Federo) Date: Sat, 09 Aug 2008 21:48:41 +0200 Subject: [Tutor] Firstrade Authentication: Form Management In-Reply-To: <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> References: <20080803164558.A7EB4981F4@www1.email.si> <1c2a2c590808031404t55d1f08q501ead2041f14fdd@mail.gmail.com> <20080804120536.7603E9B056@www1.email.si> <1c2a2c590808040704y1961be11x80aa908cb6f9d98d@mail.gmail.com> <20080808091219.22A228B9F2@www1.email.si> <1c2a2c590808080454p5cc06aechad9a4629d9617822@mail.gmail.com> Message-ID: <20080809194842.9A6A08B9F0@www1.email.si> Kent, Bellow is the last code I tried. The code open main page however down not open main page with server reply for symbol GOOG. I include in code everythig in POSTDATA. Other fields seem irelevant. Entire header is attached. Sorry for being persistent but I DO WANT to master this technology! Cheers, Ales import urllib2 import urllib opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) f = opener.open('https://investor.firstrade.com/firstrade/login.do') data = f.read() f.close() params = dict(username='janezfedero', password='kmet555', destination='') params['login.x'] = 'Log+In' params = urllib.urlencode(params) f = opener.open('https://investor.firstrade.com/firstrade/login.do', params) data = f.read() #f.close() #print(data) params2 = dict(contentProvider='pinnacor', quoteSymbol='goog', optionChain='goog', countryCode='US', optionRange='NTM', tickerSymbol='goog', ContentType='stockQuote') params2['contentProvider'] = 'pinnacor' #params2['quoteSymbol'] = 'goog' #params2['optionChain'] = 'goog' #params2['countryCode'] = 'US' #params2['optionRange'] = 'NTM' #params2['tickerSymbol'] = 'goog' #params2['contentType'] = 'stockQuote' #params2['quote.x'] = 'submitted' #params2 = 'contentProvider=pinnacor"eSymbol=goog&optionChain=goog&ountryCode=US&opti onRange=NTM&tickerSymbol=goog&contentType=stockQuote"e.x=submitted' params2 = urllib.urlencode(params2) f = opener.open ('https://investor.firstrade.com/firstrade/mainmenu.do', params2) data2 = f.read() f.close() print(data2) On Fri, 8 Aug 2008 at 13:56:29, Kent Johnson wrote: > On Fri, Aug 8, 2008 at 5:12 AM, Federo <federo at email.si> wrote: > > Kent hi > > > > I am still unable to enter data into textbox and getting back server reply. > The > > main problem is that I do not understand which fileds / header to observer > > using Firefox Fireburg. Atteched you can see headers I went through. With > red > > font I marked differences among stages. In nider of the headers I didn't > find > > fieldds you included in your workable login code. > > Hi Federo, > > This isn't really a Python question anymore, it is a matter of > figuring out what the server requires. You have to look at the form > data as well as the headers. TamperData is one Firefox pluging that > can do that, I'm sure there are others as well. > > Kent ____________________ http://www.email.si/ -------------- next part -------------- A non-text attachment was scrubbed... Name: FormManagement_VPR.doc Type: application/octet-stream Size: 153088 bytes Desc: FormManagement_VPR.doc URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/1120859c/attachment-0001.obj> From rt8396 at gmail.com Sun Aug 10 00:33:06 2008 From: rt8396 at gmail.com (r t) Date: Sat, 9 Aug 2008 17:33:06 -0500 Subject: [Tutor] running python script Message-ID: <ef018e0b0808091533w123791daw163b8d9d3c1e908f@mail.gmail.com> currently i have a batch file that is associated with .txt extentions so when i double click on a text file, windows runs the batch file that then sends command line args to MY text editor program..."Texteditor.py", instead of Microsofts *feature rich* Crappad. :-P this works, but the problem is the commad prompt stays open in the background cluttering up my desktop. So, 1. How do i close the command prompt after starting my program??? here is my one line batch script: C:\Python25\python.exe C:\Python25\TextEditor.py %1 2. or how do i do this in a much more elegant way?? i know there is a win32 ShellExecute fuction that will open a file WITHOUT "CMD" but i dont know how to make this work for what i am doing with file associations if there is a better way to do this, i am open to suggestion vista & py2.5 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080809/b30ffed1/attachment.htm> From kent37 at tds.net Sun Aug 10 19:54:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 13:54:41 -0400 Subject: [Tutor] Unable to catch exception In-Reply-To: <e107b4ff0808090928m506a05dat2b9f62286732b8ab@mail.gmail.com> References: <e107b4ff0808090928m506a05dat2b9f62286732b8ab@mail.gmail.com> Message-ID: <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> On Sat, Aug 9, 2008 at 12:28 PM, James <jtp at nc.rr.com> wrote: > All, > > I'm having a rather strange problem that I'm hoping someone can shed > some light on. I'm trying to catch a BadStatusLine exception raised by > the httplib library. > The error only happens once every blue moon, but to avoid a crash I > setup a try/catch. > > try: > <download page code here> > catch BadStatusLine: > print "yuck!" > > However, somehow the thread that this code is in still raised a > BadStatusLine exception and the thread stopped cold. How did you import BadStatusLine? One strange gotcha about except statements is that the except clause is not evaluated until an exception is raised, so you can have an invalid name and you won't know it. For example this runs fine, even though foo is not defined: In [1]: try: ...: 1 ...: except foo: ...: pass ...: Out[1]: 1 OTOH if an exception is raised it causes a NameError: In [2]: try: ...: 1/0 ...: except foo: ...: pass ...: --------------------------------------------------------------------------- <type 'exceptions.NameError'> Traceback (most recent call last) /Users/kent/<ipython console> in <module>() <type 'exceptions.NameError'>: name 'foo' is not defined Kent From bgailer at gmail.com Sun Aug 10 19:57:49 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 10 Aug 2008 13:57:49 -0400 Subject: [Tutor] IP matching?. In-Reply-To: <a250eacf0808100841r32f44438nfe5ac749177658ac@mail.gmail.com> References: <3c8f6fd70808091724x11dab42ay93df8d47334436e5@mail.gmail.com> <g7m83h$b2k$1@ger.gmane.org> <3c8f6fd70808100349q9fcfb7fj75b6898fff66e18@mail.gmail.com> <a250eacf0808100726i57199174p7a2c7040f3b46f10@mail.gmail.com> <3c8f6fd70808100738r4b44622k31a0601e28578627@mail.gmail.com> <a250eacf0808100841r32f44438nfe5ac749177658ac@mail.gmail.com> Message-ID: <489F2C1D.3010804@gmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/ff2ea4e7/attachment.htm> From kent37 at tds.net Sun Aug 10 19:56:42 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 13:56:42 -0400 Subject: [Tutor] importing path question In-Reply-To: <f52017b60808091503g49082146h22625c32f574991d@mail.gmail.com> References: <f52017b60808091503g49082146h22625c32f574991d@mail.gmail.com> Message-ID: <1c2a2c590808101056n78ea3e26mca8bf6f3c1f6c837@mail.gmail.com> On Sat, Aug 9, 2008 at 6:03 PM, dave selby <dave6502 at googlemail.com> wrote: > Hi all, > > I have a main directory 'kmotion2' where python scripts live. They > access a library of scripts in 'kmotion2/core' as 'kmotion2/core' has > a __init__.py file. However I now need to create a new directory > 'utilities' inside 'kmotion2' that also needs to access scripts in > 'core' > > kmotion2 directory > | | > core utilities > > So I need to import up the tree then back down. Is this possible ? Yes, assuming kmotion2 is in your Python path (which it should be to allow importing from core at all) you can just import core.whatever as usual. Kent From kent37 at tds.net Sun Aug 10 20:03:38 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 14:03:38 -0400 Subject: [Tutor] using generators to mock raw_input for doctest In-Reply-To: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> References: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> Message-ID: <1c2a2c590808101103u16926ef5p90bf41f0ca66594f@mail.gmail.com> On Sun, Aug 10, 2008 at 1:38 AM, <broek at cc.umanitoba.ca> wrote: > 2) Is there some better way to enable doctesting of code that uses > raw_input? All I found when googling was the suggestion that in place of: > > def myfunc(): > # code employing raw_input here > > one could write: > > def myfunc(input_meth=raw_input): > # code with raw_input calls replaced with input_meth calls > > but that seems like complicating my code for the non-doctest case. It is not going to make your code more complicated - the client code doesn't change at all and in myfunc you just change your use of raw_input() to input_meth(). If you declare def myfunc(raw_input=raw_input): you don't even have to change the body of myfunc. > class myraw(object): > def __init__(self, values): > self.values = values > self.stream = self.mygen() > def mygen(self): > for i in self.values: > yield i > def readline(self): > return str(self.stream.next()) This is needlessly complex. The values argument must be iterable (or the for loop would break) so you might as well use its iterator instead of making your own: class myraw(object): def __init__(self, values): self.stream = iter(values) def readline(self): return str(self.stream.next()) Kent From bermanrl at embarqmail.com Sun Aug 10 20:04:12 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Sun, 10 Aug 2008 14:04:12 -0400 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> References: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> Message-ID: <489F2D9C.4010002@embarqmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/f3ee3abb/attachment-0001.htm> From timothy.grant at gmail.com Sun Aug 10 20:21:02 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Sun, 10 Aug 2008 11:21:02 -0700 Subject: [Tutor] running python script In-Reply-To: <ef018e0b0808091533w123791daw163b8d9d3c1e908f@mail.gmail.com> References: <ef018e0b0808091533w123791daw163b8d9d3c1e908f@mail.gmail.com> Message-ID: <e775286d0808101121l10b15743w1b7bedf112933cb@mail.gmail.com> On Sat, Aug 9, 2008 at 3:33 PM, r t <rt8396 at gmail.com> wrote: > currently i have a batch file that is associated with .txt extentions > so when i double click on a text file, windows runs the batch file that then > sends command line args to MY text editor program..."Texteditor.py", instead > of Microsofts feature rich Crappad. :-P > this works, but the problem is the commad prompt stays open in the > background > cluttering up my desktop. > So, > 1. How do i close the command prompt after starting my program??? > > here is my one line batch script: > C:\Python25\python.exe C:\Python25\TextEditor.py %1 > > 2. or how do i do this in a much more elegant way?? > > i know there is a win32 ShellExecute fuction that will open a file WITHOUT > "CMD" > but i dont know how to make this work for what i am doing with file > associations > if there is a better way to do this, i am open to suggestion > > vista & py2.5 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Have you tried using pythonw instead of python? -- Stand Fast, tjg. [Timothy Grant] From broek at cc.umanitoba.ca Sun Aug 10 21:16:26 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 10 Aug 2008 14:16:26 -0500 Subject: [Tutor] using generators to mock raw_input for doctest In-Reply-To: <1c2a2c590808101103u16926ef5p90bf41f0ca66594f@mail.gmail.com> References: <20080810003818.emisabdig2s48c04@webware.cc.umanitoba.ca> <1c2a2c590808101103u16926ef5p90bf41f0ca66594f@mail.gmail.com> Message-ID: <20080810141626.5obl6s14c0sg08o8@webware.cc.umanitoba.ca> ----- Message from kent37 at tds.net --------- Date: Sun, 10 Aug 2008 14:03:38 -0400 From: Kent Johnson <kent37 at tds.net> Reply-To: Kent Johnson <kent37 at tds.net> Subject: Re: [Tutor] using generators to mock raw_input for doctest > On Sun, Aug 10, 2008 at 1:38 AM, <broek at cc.umanitoba.ca> wrote: > >> 2) Is there some better way to enable doctesting of code that uses >> raw_input? All I found when googling was the suggestion that in place of: >> >> def myfunc(): >> # code employing raw_input here >> >> one could write: >> >> def myfunc(input_meth=raw_input): >> # code with raw_input calls replaced with input_meth calls >> >> but that seems like complicating my code for the non-doctest case. > > It is not going to make your code more complicated - the client code > doesn't change at all and in myfunc you just change your use of > raw_input() to input_meth(). If you declare > def myfunc(raw_input=raw_input): > you don't even have to change the body of myfunc. Thanks for the reply, Kent. I didn't express myself well. What I meant was I didn't quite like the complication of the signature for no gain from the non-testing client's side. I'm thinking not that it would make the code harder to use, but rather a bit harder to figure out how to use---but I may well over-rate the cognitive overhead involved :-) <snip my smelly attempt to use a generator> > This is needlessly complex. I suspected as much :-) > The values argument must be iterable (or > the for loop would break) so you might as well use its iterator > instead of making your own: > > class myraw(object): > def __init__(self, values): > self.stream = iter(values) > def readline(self): > return str(self.stream.next()) <Smacks forehead> Thanks again, Brian vdB From broek at cc.umanitoba.ca Sun Aug 10 22:03:20 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 10 Aug 2008 15:03:20 -0500 Subject: [Tutor] puzzling EOFError when mocking raw_input in doctest Message-ID: <20080810150320.49bsbgge80ggs0g0@webware.cc.umanitoba.ca> Hi all, I've continued playing about with mocking raw_input in doctests in light of Kent's reply. I've hit an odd thing---if my substitute for raw_input returns '', I get an EOFError. The code below shows the problem. It arises equally if myrawalt is used in the doctest in place of myraw, so I am sure the problem has nothing to do with the use of iter. I can work around the problem in my actual target code---that code, like the toy code below, calls strip() on the results of raw_input, so I can get away with having my raw_input substitute return ' ' in place of ''. But, I cannot figure out why the EOFError comes up. Any thoughts? Thanks and best, Brian vdB class myraw(object): def __init__(self, values): self.stream = iter(values) def readline(self): return str(self.stream.next()) class myrawalt(object): def __init__(self, values): self.values = values self.count = 0 def readline(self): data = str(self.values[self.count]) self.count += 1 return data def double_input(): """>>> import sys >>> sys.stdin = myraw([21,3.1415]) >>> double_input(); double_input() # doctest: +ELLIPSIS 42 6.28300... >>> sys.stdin = myraw([' ',]) >>> double_input() 0 >>> sys.stdin = myraw(['',]) >>> double_input() # Failing test 0 """ val = raw_input().strip() or 0 val = float(val) * 2 val = [val, int(val)][val == int(val)] return val def __test(): import doctest doctest.testmod() if __name__ == "__main__": __test() From alan.gauld at btinternet.com Sun Aug 10 23:30:03 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Aug 2008 22:30:03 +0100 Subject: [Tutor] running python script References: <ef018e0b0808091533w123791daw163b8d9d3c1e908f@mail.gmail.com> Message-ID: <g7nml1$ufa$1@ger.gmane.org> "r t" <rt8396 at gmail.com> wrote > this works, but the problem is the commad prompt stays open in the > background cluttering up my desktop. > So, > 1. How do i close the command prompt after starting my program??? You don't. Instead you arrange for it not to open in the first place! The trick is to run the program using pythonw.exe which is associated with files ending .pyw. Thus rename your TextEdit.py to TextEdit.pyw and all should be well! > here is my one line batch script: > C:\Python25\python.exe C:\Python25\TextEditor.py %1 Or in this case substitute pythonw.exe for python.exe But to save trouble when you upgrade python I'd do two things: 1) move your textedit,py file into another folder not under python. 2) rename the file .pyw as above 3) replace the line above with START /B textedit.pyw HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Aug 10 23:58:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 17:58:55 -0400 Subject: [Tutor] IP address parse In-Reply-To: <418CDC50-66EC-47EC-BFC1-CF825A75ED12@gmail.com> References: <17285ccf0808092157k51e1eacfxc8a7f776f8950b48@mail.gmail.com> <1B02D548-2814-4259-9A5F-3224E1C2E0F6@gmail.com> <418CDC50-66EC-47EC-BFC1-CF825A75ED12@gmail.com> Message-ID: <1c2a2c590808101458g7d186942jbf381e6c50ad8eda@mail.gmail.com> On Sun, Aug 10, 2008 at 1:58 AM, Josh Rosen <rosenville at gmail.com> wrote: >> Since it doesn't look like you're doing anything with the parts of the ip >> besides writing the whole ip to a file, you can eliminate the capturing >> parentheses in your regular expression and replace them with a single pair: >> >> patt = re.compile(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})") There is no need for the outer parentheses either. Kent From xboxmuncher at gmail.com Mon Aug 11 00:09:27 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 10 Aug 2008 18:09:27 -0400 Subject: [Tutor] Download file via HTTP GET with progress monitoring & custom headers? Message-ID: <df531c470808101509k57d8bed3g2a8e1bf06f42fa1c@mail.gmail.com> I want to download a file via HTTP GET protocol (perhaps HTTP POST in the future, whatever method should allow relativly easy changes to be made to use POST later on) I need to send custom headers like in urllib2.urlrequest() I need to be able to monitor the download progress WHILE it downloads like the hook function in urllib I looked into urllib2 and it did everything except allow me to check the progress of the download during the download, it only downloads the file first with urlopen(). I also tried urllib and the reporthook function is great, except I can't send custom headers! I wish I could send a REQ object to the urlretrieve() function in urllib that way I can prepare those custom headers.. :( I was looking at the httplib library, its a little complicated/intimidating to me, maybe it can be done in this? Anyways, i would appreciate if soemone could write me a quick example to do this, or point me to the right library/funcs to do it. I want to be able to do it in native python libraries. -thanks for reading -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/11823300/attachment.htm> From jtp at nc.rr.com Mon Aug 11 00:16:38 2008 From: jtp at nc.rr.com (James) Date: Sun, 10 Aug 2008 18:16:38 -0400 Subject: [Tutor] Unable to catch exception In-Reply-To: <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> References: <e107b4ff0808090928m506a05dat2b9f62286732b8ab@mail.gmail.com> <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> Message-ID: <e107b4ff0808101516y59b52dafweb6d7a4eb9cdc0cc@mail.gmail.com> Kent, I'm not importing BadStatusLine. I'm only importing mechanize, which downloads a page repeatedly. From time to time a BadStatusLine exception is raised. I'm unsure how to go about catching it. Thoughts? -j On Sun, Aug 10, 2008 at 1:54 PM, Kent Johnson <kent37 at tds.net> wrote: > On Sat, Aug 9, 2008 at 12:28 PM, James <jtp at nc.rr.com> wrote: >> All, >> >> I'm having a rather strange problem that I'm hoping someone can shed >> some light on. I'm trying to catch a BadStatusLine exception raised by >> the httplib library. >> The error only happens once every blue moon, but to avoid a crash I >> setup a try/catch. >> >> try: >> <download page code here> >> catch BadStatusLine: >> print "yuck!" >> >> However, somehow the thread that this code is in still raised a >> BadStatusLine exception and the thread stopped cold. > > How did you import BadStatusLine? > > One strange gotcha about except statements is that the except clause > is not evaluated until an exception is raised, so you can have an > invalid name and you won't know it. For example this runs fine, even > though foo is not defined: > In [1]: try: > ...: 1 > ...: except foo: > ...: pass > ...: > Out[1]: 1 > > OTOH if an exception is raised it causes a NameError: > In [2]: try: > ...: 1/0 > ...: except foo: > ...: pass > ...: > --------------------------------------------------------------------------- > <type 'exceptions.NameError'> Traceback (most recent call last) > > /Users/kent/<ipython console> in <module>() > > <type 'exceptions.NameError'>: name 'foo' is not defined > > Kent > From kent37 at tds.net Mon Aug 11 00:18:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 18:18:40 -0400 Subject: [Tutor] puzzling EOFError when mocking raw_input in doctest In-Reply-To: <20080810150320.49bsbgge80ggs0g0@webware.cc.umanitoba.ca> References: <20080810150320.49bsbgge80ggs0g0@webware.cc.umanitoba.ca> Message-ID: <1c2a2c590808101518p3f7e577drd6a95fff267acc70@mail.gmail.com> On Sun, Aug 10, 2008 at 4:03 PM, <broek at cc.umanitoba.ca> wrote: > > Hi all, > > I've continued playing about with mocking raw_input in doctests in light of > Kent's reply. > > I've hit an odd thing---if my substitute for raw_input returns '', I get an > EOFError. The code below shows the problem. It arises equally if myrawalt is > used in the doctest in place of myraw, so I am sure the problem has nothing > to do with the use of iter. I can work around the problem in my actual > target code---that code, like the toy code below, calls strip() on the > results of raw_input, so I can get away with having my raw_input substitute > return ' ' in place of ''. But, I cannot figure out why the EOFError comes > up. Any thoughts? My guess, to verify look at the source for raw_input() or experiment... readline() normally includes the \n in the line it returns. It will only return an empty string on EOF. So the raw_input() is seeing the empty line, interpreting it as EOF, and raising EOFError. My suggestion - in your mock stdin, append a \n to the provided data. Also you might want to change the name, you are replacing sys.stdin, not raw_input(). Kent From kent37 at tds.net Mon Aug 11 00:42:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 18:42:27 -0400 Subject: [Tutor] Download file via HTTP GET with progress monitoring & custom headers? In-Reply-To: <df531c470808101509k57d8bed3g2a8e1bf06f42fa1c@mail.gmail.com> References: <df531c470808101509k57d8bed3g2a8e1bf06f42fa1c@mail.gmail.com> Message-ID: <1c2a2c590808101542r11de76f6h3f2bef4f63b96a5a@mail.gmail.com> On Sun, Aug 10, 2008 at 6:09 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > I want to download a file via HTTP GET protocol (perhaps HTTP POST in the > future, whatever method should allow relativly easy changes to be made to > use POST later on) > I need to send custom headers like in urllib2.urlrequest() > I need to be able to monitor the download progress WHILE it downloads like > the hook function in urllib > > I looked into urllib2 and it did everything except allow me to check the > progress of the download during the download, it only downloads the file > first with urlopen(). I also tried urllib and the reporthook function is > great, except I can't send custom headers! I wish I could send a REQ object > to the urlretrieve() function in urllib that way I can prepare those custom > headers.. :( > > Anyways, i would appreciate if soemone could write me a quick example to do > this, or point me to the right library/funcs to do it. I want to be able to > do it in native python libraries. urllib2.urlopen() doesn't read the data from the remote site, it returns a file-like object with a read() method. You can read the data in chunks and call a reporthook yourself. Take a look at the source to URLopener.retrieve() in urllib.py for some hints. Kent From kent37 at tds.net Mon Aug 11 00:45:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Aug 2008 18:45:11 -0400 Subject: [Tutor] Unable to catch exception In-Reply-To: <e107b4ff0808101516y59b52dafweb6d7a4eb9cdc0cc@mail.gmail.com> References: <e107b4ff0808090928m506a05dat2b9f62286732b8ab@mail.gmail.com> <1c2a2c590808101054g13c19c7co3e3a952d7734dd84@mail.gmail.com> <e107b4ff0808101516y59b52dafweb6d7a4eb9cdc0cc@mail.gmail.com> Message-ID: <1c2a2c590808101545n6eac5985wf77cef890f9eec9d@mail.gmail.com> On Sun, Aug 10, 2008 at 6:16 PM, James <jtp at nc.rr.com> wrote: > Kent, > > I'm not importing BadStatusLine. I'm only importing mechanize, which > downloads a page repeatedly. From time to time a BadStatusLine > exception is raised. I'm unsure how to go about catching it. Try adding from httplib import BadStatusLine to the top of your module. Kent From noshius at gmail.com Mon Aug 11 02:30:10 2008 From: noshius at gmail.com (Joshua Nikkel) Date: Sun, 10 Aug 2008 20:30:10 -0400 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: <b55626e20808101727k41ddab48m462429cf43fe0a45@mail.gmail.com> References: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> <489F2D9C.4010002@embarqmail.com> <b55626e20808101727k41ddab48m462429cf43fe0a45@mail.gmail.com> Message-ID: <b55626e20808101730i1c48a2beq97a469972821aa18@mail.gmail.com> ah that was it. I had a variable named len earlier. On a restart it was fine. Thanks! On Sun, Aug 10, 2008 at 2:04 PM, Robert Berman <bermanrl at embarqmail.com>wrote: > No. Not so. > > Observe, please: > Python 2.5.2 (r252:60911, May 7 2008, 15:19:09) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.2.2 ==== No Subprocess ==== > >>> import math > >>> math.sqrt(1054.12) > 32.467214232206615 > >>> s = 'supercalifragilisticexpialidocious' > >>> s > 'supercalifragilisticexpialidocious' > >>> len(s) > 34 > >>> > > Have you by any chance assigned the function len to something else? > Otherwise, it should work really well. If you do help(len) in the shell, wha > dos it tell you. > > Robert > > Joshua Nikkel wrote: > > I've pasted the following from my python shell. Please note that the first > two lines of code are taken directly from the standard tutorial files under > section 3.1.2. Will someone please tell me why something as basic and > straightforward as this will not work? Everything else seems to work just > fine, but not this. All I need is someway to get the length of a string... > > please help, > > nosh > > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.2.2 ==== No Subprocess ==== > >>> s = 'supercalifragilisticexpialidocious' > >>> len(s) > Traceback (most recent call last): > File "<pyshell#1>", line 1, in <module> > len(s) > TypeError: 'str' object is not callable > >>> s > 'supercalifragilisticexpialidocious' > >>> len(s) > Traceback (most recent call last): > File "<pyshell#3>", line 1, in <module> > len(s) > TypeError: 'str' object is not callable > >>> > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080810/9de86750/attachment.htm> From eric at ericabrahamsen.net Mon Aug 11 08:52:07 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 11 Aug 2008 14:52:07 +0800 Subject: [Tutor] requests/responses from urllib2 Message-ID: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> I've got a question about the way urllib2 makes its requests. If I've got a python web framework running behind a web server, and that framework uses urllib2 to make a request to another server, how does that traffic go in and out of my server machine? The python docs say that urllib2 requires the socket library to work, so I assume it's a socket of some sort, but I don't really understand how that socket is addressed, from the point of view of the third-party server that is receiving my urllib2 request, and returning the response. Where does it appear to be coming from? If my web server (lighttpd in this case) is set to listen on a particular port, is there any way that it can 'see' that traffic and interact with it, or is it purely between the python library and the outside world? Thanks for any enlightenment! Eric From alan.gauld at btinternet.com Mon Aug 11 10:49:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Aug 2008 09:49:28 +0100 Subject: [Tutor] requests/responses from urllib2 References: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> Message-ID: <g7oueu$l4a$1@ger.gmane.org> "Eric Abrahamsen" <eric at ericabrahamsen.net> wrote > that traffic go in and out of my server machine? The python docs say > that urllib2 requires the socket library to work, so I assume it's a > socket of some sort, but I don't really understand how that socket > is addressed, from the point of view of the third-party server that > is receiving my urllib2 request, and returning the response. Virtually all network comms is over sockets. Your web browser uses sockets every time it connects to a web server. Your web server is using sockets to receive those requests. The urllib implementation has to use the Python socket module so there is a dependency but thats just what you'd expect. It has to talk to a socket somehow and if it didn't use the socket library directly it would either use a higher level library that in turn used socket, or else it would have to implement sockets itself at the C level. > it appear to be coming from? If my web server (lighttpd in this > case) is set to listen on a particular port, is there any way that > it can 'see' that traffic and interact with it, or is it purely > between the python library and the outside world? Your web server likely listens on port 80. The urllib will send to port 80 by default. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Mon Aug 11 12:54:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Aug 2008 06:54:40 -0400 Subject: [Tutor] requests/responses from urllib2 In-Reply-To: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> References: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> Message-ID: <1c2a2c590808110354k1a879a6dm4777d446ea972994@mail.gmail.com> On Mon, Aug 11, 2008 at 2:52 AM, Eric Abrahamsen <eric at ericabrahamsen.net> wrote: The python docs say that urllib2 requires the > socket library to work, so I assume it's a socket of some sort, but I don't > really understand how that socket is addressed, from the point of view of > the third-party server that is receiving my urllib2 request, and returning > the response. Where does it appear to be coming from? The request comes from your web server, that is what the other server will see. > If my web server > (lighttpd in this case) is set to listen on a particular port, is there any > way that it can 'see' that traffic and interact with it, or is it purely > between the python library and the outside world? I'm not sure if you want to see the traffic coming in from your users, or the traffic from your server to the third-party server. I don't know what kind of interaction you want, either. Most web frameworks have a way to log the requests they receive. There may be a debug mode that includes request and response headers in the log. You could turn on debug mode in httplib, this will give you details about the outgoing traffic. I don't think it will affect the incoming traffic but I'm not certain. See http://personalpages.tds.net/~kent37/kk/00010.html#e10debugging Kent From ssmith46 at zimbra.naz.edu Mon Aug 11 14:14:30 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 08:14:30 -0400 (EDT) Subject: [Tutor] Accessing LDAP Message-ID: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> Any ideas how I can pull a list of domain users from an LDAP server and use it programmatically in a Python web application? Thanks! From dextrous85 at gmail.com Mon Aug 11 14:17:43 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Aug 2008 17:47:43 +0530 Subject: [Tutor] Accessing LDAP In-Reply-To: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> References: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <5487b3060808110517w62f3d5e2i260dfee35c293efa@mail.gmail.com> I think this can be of some help to you http://tgolden.sc.sabren.com/python/active_directory.html On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > Any ideas how I can pull a list of domain users from an LDAP server and use > it programmatically in a Python web application? > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/d07077f7/attachment.htm> From rudy.schockaert at gmail.com Mon Aug 11 15:04:50 2008 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Mon, 11 Aug 2008 15:04:50 +0200 Subject: [Tutor] Accessing LDAP In-Reply-To: <5487b3060808110517w62f3d5e2i260dfee35c293efa@mail.gmail.com> References: <1910299968.6454291218456870850.JavaMail.root@nazoli1.optimizedlearn.com> <5487b3060808110517w62f3d5e2i260dfee35c293efa@mail.gmail.com> Message-ID: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> If by LDAP server you mean Active Directory, then Tim's active_directory module is certainly the way to go. If you want a more generic LDAP approach, you could give python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com>wrote: > I think this can be of some help to you > http://tgolden.sc.sabren.com/python/active_directory.html > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > >> Any ideas how I can pull a list of domain users from an LDAP server and >> use it programmatically in a Python web application? >> >> Thanks! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/58f01b4a/attachment.htm> From ssmith46 at zimbra.naz.edu Mon Aug 11 15:13:28 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 09:13:28 -0400 (EDT) Subject: [Tutor] Accessing LDAP In-Reply-To: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> Message-ID: <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> It is indeed an active directory server, but the sysadmin tells me that it is configured to respond to normal ldap queries as well. I tried Tim's module, and it's giving me an "operations error" when I try to use his code snippet to list users... ----- Original Message ----- From: "Rudy Schockaert" <rudy.schockaert at gmail.com> To: "vishwajeet singh" <dextrous85 at gmail.com> Cc: "Steven L Smith" <ssmith46 at naz.edu>, "tutor" <tutor at python.org> Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York Subject: Re: [Tutor] Accessing LDAP If by LDAP server you mean Active Directory, then Tim's active_directory module is certainly the way to go. If you want a more generic LDAP approach, you could give python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com>wrote: > I think this can be of some help to you > http://tgolden.sc.sabren.com/python/active_directory.html > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > >> Any ideas how I can pull a list of domain users from an LDAP server and >> use it programmatically in a Python web application? >> >> Thanks! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From dextrous85 at gmail.com Mon Aug 11 15:15:38 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Aug 2008 18:45:38 +0530 Subject: [Tutor] Accessing LDAP In-Reply-To: <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> References: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <5487b3060808110615we5a60f1w37a4e59de728e5e4@mail.gmail.com> I have used it and it works pretty well for me.Can you show the code snippet you are trying to execute?? On Mon, Aug 11, 2008 at 6:43 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > It is indeed an active directory server, but the sysadmin tells me that it > is configured to respond to normal ldap queries as well. > > I tried Tim's module, and it's giving me an "operations error" when I try > to use his code snippet to list users... > > > ----- Original Message ----- > From: "Rudy Schockaert" <rudy.schockaert at gmail.com> > To: "vishwajeet singh" <dextrous85 at gmail.com> > Cc: "Steven L Smith" <ssmith46 at naz.edu>, "tutor" <tutor at python.org> > Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York > Subject: Re: [Tutor] Accessing LDAP > > If by LDAP server you mean Active Directory, then Tim's active_directory > module is certainly the way to go. > If you want a more generic LDAP approach, you could give > python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. > > On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com > >wrote: > > > I think this can be of some help to you > > http://tgolden.sc.sabren.com/python/active_directory.html > > > > > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu > >wrote: > > > >> Any ideas how I can pull a list of domain users from an LDAP server and > >> use it programmatically in a Python web application? > >> > >> Thanks! > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > -- > > Cheers, > > Vishwajeet > > http://www.singhvishwajeet.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/f4bc713c/attachment-0001.htm> From ssmith46 at zimbra.naz.edu Mon Aug 11 15:21:02 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 09:21:02 -0400 (EDT) Subject: [Tutor] Accessing LDAP In-Reply-To: <5487b3060808110615we5a60f1w37a4e59de728e5e4@mail.gmail.com> Message-ID: <923693530.6467611218460862676.JavaMail.root@nazoli1.optimizedlearn.com> <% import active_directory for person in active_directory.search ("objectCategory='Person'"): Response.Write(person.displayName) %> Results in... Python ActiveX Scripting Engine error '80020009' Traceback (most recent call last): File "<Script Block >", line 17, in <module> for person in active_directory.search ("objectCategory='Person'"): File "C:\Python25\Lib\site-packages\active_directory.py", line 747, in search return root ().search (*args, **kwargs) File "C:\Python25\Lib\site-packages\active_directory.py", line 743, in root _ad = AD () File "C:\Python25\Lib\site-packages\active_directory.py", line 712, in AD return AD_object (GetObject ("LDAP://%s" % default_naming_context)) File "C:\Python25\Lib\site-packages\win32com\client\__init__.py", line 73, in GetObject return Moniker(Pathname, clsctx) File "C:\Python25\Lib\site-packages\win32com\client\__init__.py", line 88, in Moniker moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname) COM Error: An operations error occurred. (0x-7ff8dfe0) /metaproject/index.asp, line 121 ----- Original Message ----- From: "vishwajeet singh" <dextrous85 at gmail.com> To: "Steven L Smith" <ssmith46 at naz.edu> Cc: "tutor" <tutor at python.org> Sent: Monday, August 11, 2008 9:15:38 AM (GMT-0500) America/New_York Subject: Re: [Tutor] Accessing LDAP I have used it and it works pretty well for me.Can you show the code snippet you are trying to execute?? On Mon, Aug 11, 2008 at 6:43 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > It is indeed an active directory server, but the sysadmin tells me that it > is configured to respond to normal ldap queries as well. > > I tried Tim's module, and it's giving me an "operations error" when I try > to use his code snippet to list users... > > > ----- Original Message ----- > From: "Rudy Schockaert" <rudy.schockaert at gmail.com> > To: "vishwajeet singh" <dextrous85 at gmail.com> > Cc: "Steven L Smith" <ssmith46 at naz.edu>, "tutor" <tutor at python.org> > Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York > Subject: Re: [Tutor] Accessing LDAP > > If by LDAP server you mean Active Directory, then Tim's active_directory > module is certainly the way to go. > If you want a more generic LDAP approach, you could give > python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. > > On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com > >wrote: > > > I think this can be of some help to you > > http://tgolden.sc.sabren.com/python/active_directory.html > > > > > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu > >wrote: > > > >> Any ideas how I can pull a list of domain users from an LDAP server and > >> use it programmatically in a Python web application? > >> > >> Thanks! > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > -- > > Cheers, > > Vishwajeet > > http://www.singhvishwajeet.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com From dextrous85 at gmail.com Mon Aug 11 15:33:07 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Aug 2008 19:03:07 +0530 Subject: [Tutor] Accessing LDAP In-Reply-To: <923693530.6467611218460862676.JavaMail.root@nazoli1.optimizedlearn.com> References: <5487b3060808110615we5a60f1w37a4e59de728e5e4@mail.gmail.com> <923693530.6467611218460862676.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <5487b3060808110633y1264ec37rb601844b14e9c4d0@mail.gmail.com> I am not able to reproduce the problem as it works pretty fine at my end. On Mon, Aug 11, 2008 at 6:51 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > <% > import active_directory > for person in active_directory.search ("objectCategory='Person'"): > Response.Write(person.displayName) > %> > > Results in... > > Python ActiveX Scripting Engine error '80020009' > > Traceback (most recent call last): File "<Script Block >", line 17, in > <module> for person in active_directory.search ("objectCategory='Person'"): > File "C:\Python25\Lib\site-packages\active_directory.py", line 747, in > search return root ().search (*args, **kwargs) File > "C:\Python25\Lib\site-packages\active_directory.py", line 743, in root _ad = > AD () File "C:\Python25\Lib\site-packages\active_directory.py", line 712, in > AD return AD_object (GetObject ("LDAP://%s" % default_naming_context)) File > "C:\Python25\Lib\site-packages\win32com\client\__init__.py", line 73, in > GetObject return Moniker(Pathname, clsctx) File > "C:\Python25\Lib\site-packages\win32com\client\__init__.py", line 88, in > Moniker moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname) COM > Error: An operations error occurred. (0x-7ff8dfe0) > > /metaproject/index.asp, line 121 > > > ----- Original Message ----- > From: "vishwajeet singh" <dextrous85 at gmail.com> > To: "Steven L Smith" <ssmith46 at naz.edu> > Cc: "tutor" <tutor at python.org> > Sent: Monday, August 11, 2008 9:15:38 AM (GMT-0500) America/New_York > Subject: Re: [Tutor] Accessing LDAP > > I have used it and it works pretty well for me.Can you show the code > snippet > you are trying to execute?? > > On Mon, Aug 11, 2008 at 6:43 PM, Steven L Smith <ssmith46 at zimbra.naz.edu > >wrote: > > > It is indeed an active directory server, but the sysadmin tells me that > it > > is configured to respond to normal ldap queries as well. > > > > I tried Tim's module, and it's giving me an "operations error" when I try > > to use his code snippet to list users... > > > > > > ----- Original Message ----- > > From: "Rudy Schockaert" <rudy.schockaert at gmail.com> > > To: "vishwajeet singh" <dextrous85 at gmail.com> > > Cc: "Steven L Smith" <ssmith46 at naz.edu>, "tutor" <tutor at python.org> > > Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York > > Subject: Re: [Tutor] Accessing LDAP > > > > If by LDAP server you mean Active Directory, then Tim's active_directory > > module is certainly the way to go. > > If you want a more generic LDAP approach, you could give > > python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. > > > > On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com > > >wrote: > > > > > I think this can be of some help to you > > > http://tgolden.sc.sabren.com/python/active_directory.html > > > > > > > > > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith < > ssmith46 at zimbra.naz.edu > > >wrote: > > > > > >> Any ideas how I can pull a list of domain users from an LDAP server > and > > >> use it programmatically in a Python web application? > > >> > > >> Thanks! > > >> _______________________________________________ > > >> Tutor maillist - Tutor at python.org > > >> http://mail.python.org/mailman/listinfo/tutor > > >> > > > > > > > > > > > > -- > > > Cheers, > > > Vishwajeet > > > http://www.singhvishwajeet.com > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/ac3ea464/attachment.htm> From rudy.schockaert at gmail.com Mon Aug 11 17:37:35 2008 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Mon, 11 Aug 2008 17:37:35 +0200 Subject: [Tutor] Accessing LDAP In-Reply-To: <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> References: <60987dac0808110604o24534128g987ec60f8c605464@mail.gmail.com> <521957028.6465931218460408221.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <60987dac0808110837q29d2836dsa51818522712dd01@mail.gmail.com> Ok, then you best stick to Tim's module. Are you running your script from a workstation or server in the forest? What I always try first in interactive mode is the following: import active_directory ad = active_directory.AD() print ad That should already show you if you can connect to AD or not. On Mon, Aug 11, 2008 at 3:13 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > It is indeed an active directory server, but the sysadmin tells me that it > is configured to respond to normal ldap queries as well. > > I tried Tim's module, and it's giving me an "operations error" when I try > to use his code snippet to list users... > > > ----- Original Message ----- > From: "Rudy Schockaert" <rudy.schockaert at gmail.com> > To: "vishwajeet singh" <dextrous85 at gmail.com> > Cc: "Steven L Smith" <ssmith46 at naz.edu>, "tutor" <tutor at python.org> > Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York > Subject: Re: [Tutor] Accessing LDAP > > If by LDAP server you mean Active Directory, then Tim's active_directory > module is certainly the way to go. > If you want a more generic LDAP approach, you could give > python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. > > On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com > >wrote: > > > I think this can be of some help to you > > http://tgolden.sc.sabren.com/python/active_directory.html > > > > > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu > >wrote: > > > >> Any ideas how I can pull a list of domain users from an LDAP server and > >> use it programmatically in a Python web application? > >> > >> Thanks! > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > -- > > Cheers, > > Vishwajeet > > http://www.singhvishwajeet.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/b0e85ebd/attachment.htm> From alan.gauld at btinternet.com Mon Aug 11 17:42:20 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 11 Aug 2008 15:42:20 +0000 (GMT) Subject: [Tutor] Problems with Gauge Bar. Message-ID: <542659.81506.qm@web86704.mail.ukl.yahoo.com> Including the list - please use ReplyAll. Its the file that you want to scan - assuming there is a file. It could be a list or anything else - I don't actually know from your code what onScan is supposed to do! :-) > Well, My code is supposed to do a lot. My actual onScan looks like this: def OnScan(self, event): startScan = '''TSO will now start creating a log. Please be patient as this can take from 5 up to 10 minutes. Please press OK to start TSO.''' dlg2 = wx.MessageDialog(self, startScan, 'Starting TSO.', wx.OK|wx.ICON_INFORMATION) dlg2.ShowModal() dlg2.Destroy() scan() dlg = wx.MessageDialog(self, 'The log is done.\n Press OK to return to TSO.', 'Done Creating Log.', wx.OK|wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() > the part that calls for the features in TSO (scan()) is simply defined later in the program > (out of the class I might add). Is this a problem for the gauge bar? Possibly. For the guage to display progress it needs a way to get the intermediate progress. If the scan() function updates some global variable or has a hook function to call for periodic update then all is well. But if it is a single monolithic bit of code there is very little you can do. Given the scan() function is external to the GUI - as it should be - then I'd probably opt for running scan() inside a thread and using a non-modal dialog to indicate that the scan is running - maybe with a simple timer display to show that its still running. Then at the end of the scam either just delete the dialog or bring it to the top to make the user delete it - thus seeing that the scan is complete. By making it non-modal the user can carry on using the GUI while scanning. > (Let me know if you need to know the complete scan() code as well. Probably not since I'm guessing it is basically a single loop with no breakouts or callback hooks. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/211a77d7/attachment-0001.htm> From ssmith46 at zimbra.naz.edu Mon Aug 11 17:51:25 2008 From: ssmith46 at zimbra.naz.edu (Steven L Smith) Date: Mon, 11 Aug 2008 11:51:25 -0400 (EDT) Subject: [Tutor] Accessing LDAP In-Reply-To: <1401908804.6501471218469846775.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <1780422933.6501681218469885607.JavaMail.root@nazoli1.optimizedlearn.com> Hmmm... well, that worked, and the previous code snippet worked in interactive mode too... maybe there's something wrong with the user that IIS is running under? How would I give it the proper permissions? ----- Original Message ----- From: "Rudy Schockaert" <rudy.schockaert at gmail.com> To: "Steven L Smith" <ssmith46 at naz.edu> Cc: "tutor" <tutor at python.org> Sent: Monday, August 11, 2008 11:37:35 AM (GMT-0500) America/New_York Subject: Re: [Tutor] Accessing LDAP Ok, then you best stick to Tim's module. Are you running your script from a workstation or server in the forest? What I always try first in interactive mode is the following: import active_directory ad = active_directory.AD() print ad That should already show you if you can connect to AD or not. On Mon, Aug 11, 2008 at 3:13 PM, Steven L Smith <ssmith46 at zimbra.naz.edu>wrote: > It is indeed an active directory server, but the sysadmin tells me that it > is configured to respond to normal ldap queries as well. > > I tried Tim's module, and it's giving me an "operations error" when I try > to use his code snippet to list users... > > > ----- Original Message ----- > From: "Rudy Schockaert" <rudy.schockaert at gmail.com> > To: "vishwajeet singh" <dextrous85 at gmail.com> > Cc: "Steven L Smith" <ssmith46 at naz.edu>, "tutor" <tutor at python.org> > Sent: Monday, August 11, 2008 9:04:50 AM (GMT-0500) America/New_York > Subject: Re: [Tutor] Accessing LDAP > > If by LDAP server you mean Active Directory, then Tim's active_directory > module is certainly the way to go. > If you want a more generic LDAP approach, you could give > python-ldap<http://python-ldap.sourceforge.net/download.shtml>a try. > > On Mon, Aug 11, 2008 at 2:17 PM, vishwajeet singh <dextrous85 at gmail.com > >wrote: > > > I think this can be of some help to you > > http://tgolden.sc.sabren.com/python/active_directory.html > > > > > > > > On Mon, Aug 11, 2008 at 5:44 PM, Steven L Smith <ssmith46 at zimbra.naz.edu > >wrote: > > > >> Any ideas how I can pull a list of domain users from an LDAP server and > >> use it programmatically in a Python web application? > >> > >> Thanks! > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > -- > > Cheers, > > Vishwajeet > > http://www.singhvishwajeet.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Aug 11 18:04:00 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Aug 2008 17:04:00 +0100 Subject: [Tutor] Accessing LDAP References: <5487b3060808110615we5a60f1w37a4e59de728e5e4@mail.gmail.com> <923693530.6467611218460862676.JavaMail.root@nazoli1.optimizedlearn.com> Message-ID: <g7pntf$cc8$1@ger.gmane.org> "Steven L Smith" <ssmith46 at zimbra.naz.edu> wrote > <% > import active_directory > for person in active_directory.search ("objectCategory='Person'"): > Response.Write(person.displayName) > %> > > Results in... > > Python ActiveX Scripting Engine error '80020009' Do you have the right access rights? Just a guess... Alan g From lauren at protopc.com Mon Aug 11 18:26:16 2008 From: lauren at protopc.com (lauren at protopc.com) Date: Mon, 11 Aug 2008 10:26:16 -0600 (MDT) Subject: [Tutor] How to reference a wx.grid.Grid outside the method inwhich it was created? Message-ID: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> I have created a wx.grid.Grid attached to a panel which is attached to a frame within one method (Method #1). Inside this method I also created a combobox. When an item is selected in the combobox another method is called (i.e. When the event is called the method is run ) Inside this method I want to fill the grid created in Method #1 with data generated/calculated from within Method #2 based on which item was selected from the combobox. How do I reference the grid from method #1 when I am in method #2? Currently I am receving this error message: "NameError: global name 'myGrid' is not defined." It's an error against this statement in method #2: myGrid.SetCellValue(i, 0, myValue) Thanks! Lauren From kent37 at tds.net Mon Aug 11 18:45:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Aug 2008 12:45:40 -0400 Subject: [Tutor] How to reference a wx.grid.Grid outside the method inwhich it was created? In-Reply-To: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> References: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> Message-ID: <1c2a2c590808110945y739b4e1ey87f60af0212e9a9c@mail.gmail.com> On Mon, Aug 11, 2008 at 12:26 PM, <lauren at protopc.com> wrote: > I have created a wx.grid.Grid attached to a panel which is attached to a > frame within one method (Method #1). Inside this method I also created a > combobox. > > When an item is selected in the combobox another method is called (i.e. > When the event is called the method is run?) > Inside this method I want to fill the grid created in Method #1 with data > generated/calculated from within Method #2 based on which item was > selected from the combobox. > > How do I reference the grid from method #1 when I am in method #2? > > Currently I am receving this error message: > "NameError: global name 'myGrid' is not defined." > > It's an error against this statement in method #2: > myGrid.SetCellValue(i, 0, myValue) If method1 and method2 are both methods of the same class, just save myGrid as an attribute of the class rather than having it as a local variable in method1. I.e. def method1(self): self.myGrid = ... def method2(self): self.myGrid.SetCellValue(...) Kent From lauren at protopc.com Mon Aug 11 20:07:41 2008 From: lauren at protopc.com (lauren at protopc.com) Date: Mon, 11 Aug 2008 12:07:41 -0600 (MDT) Subject: [Tutor] How to reference a wx.grid.Grid outside the method inwhich it was created? In-Reply-To: <1c2a2c590808110945y739b4e1ey87f60af0212e9a9c@mail.gmail.com> References: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> <1c2a2c590808110945y739b4e1ey87f60af0212e9a9c@mail.gmail.com> Message-ID: <34936.69.16.140.5.1218478061.squirrel@www.protopc.com> It worked like a charm! Thank you so much!! Lauren > If method1 and method2 are both methods of the same class, just save > myGrid as an attribute of the class rather than having it as a local > variable in method1. I.e. > > def method1(self): > self.myGrid = ... > > def method2(self): > self.myGrid.SetCellValue(...) > > Kent > From o.lenstra at gmail.com Tue Aug 12 00:15:08 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Tue, 12 Aug 2008 00:15:08 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <542659.81506.qm@web86704.mail.ukl.yahoo.com> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> Message-ID: <3c8f6fd70808111515p4750d4e1s923c7b553dbf0d3d@mail.gmail.com> > Including the list - please use ReplyAll. > Sorry. Pressed the wrong button. > > > Its the file that you want to scan - assuming there is a file. >> It could be a list or anything else - I don't actually know from >> your code what onScan is supposed to do! :-) > > > > Well, My code is supposed to do a lot. My actual onScan looks like this: > > def OnScan(self, event): > startScan = '''TSO will now start creating a log. > Please be patient as this can take from 5 up to 10 minutes. > Please press OK to start TSO.''' > dlg2 = wx.MessageDialog(self, startScan, 'Starting TSO.', > wx.OK|wx.ICON_INFORMATION) > dlg2.ShowModal() > dlg2.Destroy() > > scan() > > dlg = wx.MessageDialog(self, 'The log is done.\n Press OK to return > to TSO.', > 'Done Creating Log.', > wx.OK|wx.ICON_INFORMATION) > dlg.ShowModal() > dlg.Destroy() > > > the part that calls for the features in TSO (scan()) is simply defined > later in the program > > (out of the class I might add). Is this a problem for the gauge bar? > > Possibly. For the guage to display progress it needs a way to get the > intermediate > progress. If the scan() function updates some global variable or has a hook > function > to call for periodic update then all is well. But if it is a single > monolithic bit of code > there is very little you can do. > Not sure what you mean. My code calls different built in functions from windows. (Like Ipconfig, ping etc.) The only thing I do is call them from python, make sure that the format is right and write it to a file. (called temp.txt) Once temp.txt is complete it goes through a script which makes the text 'cross platform' so it shows 'nice' on forums. I'll make a little attempt to this. Not sure how it will go. > > > Given the scan() function is external to the GUI - as it should be - then > I'd probably > opt for running scan() inside a thread and using a non-modal dialog to > indicate that > the scan is running - maybe with a simple timer display to show that its > still running. > Then at the end of the scam either just delete the dialog or bring it to > the top to make > the user delete it - thus seeing that the scan is complete. By making it > non-modal > the user can carry on using the GUI while scanning. > Yes the scan() functions are external to the GUI. I simply made the code first and the GUI later. > > > (Let me know if you need to know the complete scan() code as well. > Probably not since I'm guessing it is basically a single loop with no > breakouts > or callback hooks. > I'll take your word for that. ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080812/98368d77/attachment.htm> From o.lenstra at gmail.com Tue Aug 12 00:16:05 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Tue, 12 Aug 2008 00:16:05 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <542659.81506.qm@web86704.mail.ukl.yahoo.com> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> Message-ID: <3c8f6fd70808111516u68b9d25evb33432a50177a068@mail.gmail.com> > Including the list - please use ReplyAll. > Sorry. Pressed the wrong button. > > > Its the file that you want to scan - assuming there is a file. >> It could be a list or anything else - I don't actually know from >> your code what onScan is supposed to do! :-) > > > > Well, My code is supposed to do a lot. My actual onScan looks like this: > > def OnScan(self, event): > startScan = '''TSO will now start creating a log. > Please be patient as this can take from 5 up to 10 minutes. > Please press OK to start TSO.''' > dlg2 = wx.MessageDialog(self, startScan, 'Starting TSO.', > wx.OK|wx.ICON_INFORMATION) > dlg2.ShowModal() > dlg2.Destroy() > > scan() > > dlg = wx.MessageDialog(self, 'The log is done.\n Press OK to return > to TSO.', > 'Done Creating Log.', > wx.OK|wx.ICON_INFORMATION) > dlg.ShowModal() > dlg.Destroy() > > > the part that calls for the features in TSO (scan()) is simply defined > later in the program > > (out of the class I might add). Is this a problem for the gauge bar? > > Possibly. For the guage to display progress it needs a way to get the > intermediate > progress. If the scan() function updates some global variable or has a hook > function > to call for periodic update then all is well. But if it is a single > monolithic bit of code > there is very little you can do. > Not sure what you mean. My code calls different built in functions from windows. (Like Ipconfig, ping etc.) The only thing I do is call them from python, make sure that the format is right and write it to a file. (called temp.txt) Once temp.txt is complete it goes through a script which makes the text 'cross platform' so it shows 'nice' on forums. I'll make a little attempt to this. Not sure how it will go. > > > Given the scan() function is external to the GUI - as it should be - then > I'd probably > opt for running scan() inside a thread and using a non-modal dialog to > indicate that > the scan is running - maybe with a simple timer display to show that its > still running. > Then at the end of the scam either just delete the dialog or bring it to > the top to make > the user delete it - thus seeing that the scan is complete. By making it > non-modal > the user can carry on using the GUI while scanning. > Yes the scan() functions are external to the GUI. I simply made the code first and the GUI later. > > > (Let me know if you need to know the complete scan() code as well. > Probably not since I'm guessing it is basically a single loop with no > breakouts > or callback hooks. > I'll take your word for that. ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080812/49db6bca/attachment-0001.htm> From o.lenstra at gmail.com Tue Aug 12 00:20:38 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Tue, 12 Aug 2008 00:20:38 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <542659.81506.qm@web86704.mail.ukl.yahoo.com> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> Message-ID: <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> > Including the list - please use ReplyAll. > Sorry. Pressed the wrong button. > > > Its the file that you want to scan - assuming there is a file. >> It could be a list or anything else - I don't actually know from >> your code what onScan is supposed to do! :-) > > > > Well, My code is supposed to do a lot. My actual onScan looks like this: > > def OnScan(self, event): > startScan = '''TSO will now start creating a log. > Please be patient as this can take from 5 up to 10 minutes. > Please press OK to start TSO.''' > dlg2 = wx.MessageDialog(self, startScan, 'Starting TSO.', > wx.OK|wx.ICON_INFORMATION) > dlg2.ShowModal() > dlg2.Destroy() > > scan() > > dlg = wx.MessageDialog(self, 'The log is done.\n Press OK to return > to TSO.', > 'Done Creating Log.', > wx.OK|wx.ICON_INFORMATION) > dlg.ShowModal() > dlg.Destroy() > > > the part that calls for the features in TSO (scan()) is simply defined > later in the program > > (out of the class I might add). Is this a problem for the gauge bar? > > Possibly. For the guage to display progress it needs a way to get the > intermediate > progress. If the scan() function updates some global variable or has a hook > function > to call for periodic update then all is well. But if it is a single > monolithic bit of code > there is very little you can do. > Not sure what you mean. My code calls different built in functions from windows. (Like Ipconfig, ping etc.) The only thing I do is call them from python, make sure that the format is right and write it to a file. (called temp.txt) Once temp.txt is complete it goes through a script which makes the text 'cross platform' so it shows 'nice' on forums. I'll make a little attempt to this. Not sure how it will go. > > > Given the scan() function is external to the GUI - as it should be - then > I'd probably > opt for running scan() inside a thread and using a non-modal dialog to > indicate that > the scan is running - maybe with a simple timer display to show that its > still running. > Then at the end of the scam either just delete the dialog or bring it to > the top to make > the user delete it - thus seeing that the scan is complete. By making it > non-modal > the user can carry on using the GUI while scanning. > Yes the scan() functions are external to the GUI. I simply made the code first and the GUI later. > > > (Let me know if you need to know the complete scan() code as well. > Probably not since I'm guessing it is basically a single loop with no > breakouts > or callback hooks. > I'll take your word for that. ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080812/4005b141/attachment.htm> From xboxmuncher at gmail.com Tue Aug 12 00:47:35 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 11 Aug 2008 18:47:35 -0400 Subject: [Tutor] Download file via HTTP GET with progress monitoring & custom headers? In-Reply-To: <1c2a2c590808101542r11de76f6h3f2bef4f63b96a5a@mail.gmail.com> References: <df531c470808101509k57d8bed3g2a8e1bf06f42fa1c@mail.gmail.com> <1c2a2c590808101542r11de76f6h3f2bef4f63b96a5a@mail.gmail.com> Message-ID: <df531c470808111547t65cbe770w2c35faab1600fc6b@mail.gmail.com> Thanks Kent! Here's what I got, works pretty well. :) import urllib2 #functions def reportDownloadProgress(blocknum, bs, size): percent = int(blocknum*bs*100/size) print str(blocknum*bs ) + '/' + str(size) + 'downloaded| ' + str(percent) + '%' def httpDownload(url, filename, headers=None, reporthook=None, postData=None): reqObj = urllib2.Request(url, postData, headers) fp = urllib2.urlopen(reqObj) headers = fp.info() ## This function returns a file-like object with two additional methods: ## ## * geturl() -- return the URL of the resource retrieved ## * info() -- return the meta-information of the page, as a dictionary-like object ## ##Raises URLError on errors. ## ##Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). #read & write fileObj to filename tfp = open(filename, 'wb') result = filename, headers bs = 1024*8 size = -1 read = 0 blocknum = 0 if reporthook: if "content-length" in headers: size = int(headers["Content-Length"]) reporthook(blocknum, bs, size) while 1: block = fp.read(bs) if block == "": break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) fp.close() tfp.close() del fp del tfp # raise exception if actual size does not match content-length header if size >= 0 and read < size: raise ContentTooShortError("retrieval incomplete: got only %i out " "of %i bytes" % (read, size), result) return result url = ' http://akvideos.metacafe.com/ItemFiles/%5BFrom%20www.metacafe.com%5D%20292662.2155544.11.flv ' headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', 'Accept' : 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language' : 'fr-fr,en-us;q=0.7,en;q=0.3', 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' } #test it httpDownload(url, 'testDownload.flv', headers, reportDownloadProgress) On Sun, Aug 10, 2008 at 6:42 PM, Kent Johnson <kent37 at tds.net> wrote: > On Sun, Aug 10, 2008 at 6:09 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > > I want to download a file via HTTP GET protocol (perhaps HTTP POST in the > > future, whatever method should allow relativly easy changes to be made to > > use POST later on) > > I need to send custom headers like in urllib2.urlrequest() > > I need to be able to monitor the download progress WHILE it downloads > like > > the hook function in urllib > > > > I looked into urllib2 and it did everything except allow me to check the > > progress of the download during the download, it only downloads the file > > first with urlopen(). I also tried urllib and the reporthook function is > > great, except I can't send custom headers! I wish I could send a REQ > object > > to the urlretrieve() function in urllib that way I can prepare those > custom > > headers.. :( > > > > Anyways, i would appreciate if soemone could write me a quick example to > do > > this, or point me to the right library/funcs to do it. I want to be able > to > > do it in native python libraries. > > urllib2.urlopen() doesn't read the data from the remote site, it > returns a file-like object with a read() method. You can read the data > in chunks and call a reporthook yourself. > > Take a look at the source to URLopener.retrieve() in urllib.py for some > hints. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/a6e26a55/attachment.htm> From alan.gauld at btinternet.com Tue Aug 12 01:27:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Aug 2008 00:27:15 +0100 Subject: [Tutor] How to reference a wx.grid.Grid outside the method inwhich it was created? References: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> Message-ID: <g7qhsf$2br$1@ger.gmane.org> <lauren at protopc.com> wrote Currently I am receving this error message: "NameError: global name 'myGrid' is not defined." It's an error against this statement in method #2: myGrid.SetCellValue(i, 0, myValue) As a general rule when posting to the list include the full error trace not just a summary. The tracelback often has useful info. In this case it wasn't needed however. :-) Alan G. From ricaraoz at gmail.com Mon Aug 11 16:16:02 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 11 Aug 2008 11:16:02 -0300 Subject: [Tutor] something is fundamentally wrong... In-Reply-To: <b55626e20808101730i1c48a2beq97a469972821aa18@mail.gmail.com> References: <b55626e20808090845k67db91a7o460810c883b01a28@mail.gmail.com> <489F2D9C.4010002@embarqmail.com> <b55626e20808101727k41ddab48m462429cf43fe0a45@mail.gmail.com> <b55626e20808101730i1c48a2beq97a469972821aa18@mail.gmail.com> Message-ID: <48A049A2.6020200@bigfoot.com> Joshua Nikkel wrote: > > ah that was it. I had a variable named len earlier. On a restart it > was fine. Thanks! > Besides that you have a HUGE error!!! Your spelling! It should be : >>> s = 'supercalifragilisticoexpialidoso' :P > > On Sun, Aug 10, 2008 at 2:04 PM, Robert Berman <bermanrl at embarqmail.com > <mailto:bermanrl at embarqmail.com>> wrote: > > No. Not so. > > Observe, please: > Python 2.5.2 (r252:60911, May 7 2008, 15:19:09) > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 > > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.2.2 ==== No Subprocess ==== > >>> import math > >>> math.sqrt(1054.12) > 32.467214232206615 > >>> s = 'supercalifragilisticexpialidocious' > >>> s > 'supercalifragilisticexpialidocious' > >>> len(s) > 34 > >>> > > Have you by any chance assigned the function len to something else? > Otherwise, it should work really well. If you do help(len) in the > shell, wha dos it tell you. > > Robert > > Joshua Nikkel wrote: >> I've pasted the following from my python shell. Please note that >> the first two lines of code are taken directly from the standard >> tutorial files under section 3.1.2. <http://3.1.2.> Will someone >> please tell me why something as basic and straightforward as this >> will not work? Everything else seems to work just fine, but not >> this. All I need is someway to get the length of a string... >> >> please help, >> >> nosh >> >> >> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 >> bit (Intel)] on win32 >> Type "copyright", "credits" or "license()" for more information. >> >> **************************************************************** >> Personal firewall software may warn about the connection IDLE >> makes to its subprocess using this computer's internal loopback >> interface. This connection is not visible on any external >> interface and no data is sent to or received from the Internet. >> **************************************************************** >> >> IDLE 1.2.2 ==== No Subprocess ==== >> >>> s = 'supercalifragilisticexpialidocious' >> >>> len(s) >> Traceback (most recent call last): >> File "<pyshell#1>", line 1, in <module> >> len(s) >> TypeError: 'str' object is not callable >> >>> s >> 'supercalifragilisticexpialidocious' >> >>> len(s) >> Traceback (most recent call last): >> File "<pyshell#3>", line 1, in <module> >> len(s) >> TypeError: 'str' object is not callable >> >>> From kent37 at tds.net Tue Aug 12 02:58:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Aug 2008 20:58:45 -0400 Subject: [Tutor] Download file via HTTP GET with progress monitoring & custom headers? In-Reply-To: <df531c470808111547t65cbe770w2c35faab1600fc6b@mail.gmail.com> References: <df531c470808101509k57d8bed3g2a8e1bf06f42fa1c@mail.gmail.com> <1c2a2c590808101542r11de76f6h3f2bef4f63b96a5a@mail.gmail.com> <df531c470808111547t65cbe770w2c35faab1600fc6b@mail.gmail.com> Message-ID: <1c2a2c590808111758q54802ea0ra6675a81e413d359@mail.gmail.com> On Mon, Aug 11, 2008 at 6:47 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > Thanks Kent! > Here's what I got, works pretty well. :) Looks OK to me except this is not needed: > del fp > del tfp The variables will go out of scope when the function exits anyway. Kent From lauren at protopc.com Tue Aug 12 07:40:54 2008 From: lauren at protopc.com (Lauren Snyder) Date: Mon, 11 Aug 2008 22:40:54 -0700 Subject: [Tutor] How to reference a wx.grid.Grid outside the methodinwhich it was created? In-Reply-To: <g7qhsf$2br$1@ger.gmane.org> References: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> <g7qhsf$2br$1@ger.gmane.org> Message-ID: <08A3FCE023ED4C65B4E54E25D4DEB005@laurenpc> Will do! Thanks again, Lauren :-) -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld Sent: Monday, August 11, 2008 4:27 PM To: tutor at python.org Subject: Re: [Tutor] How to reference a wx.grid.Grid outside the methodinwhich it was created? <lauren at protopc.com> wrote Currently I am receving this error message: "NameError: global name 'myGrid' is not defined." It's an error against this statement in method #2: myGrid.SetCellValue(i, 0, myValue) As a general rule when posting to the list include the full error trace not just a summary. The tracelback often has useful info. In this case it wasn't needed however. :-) Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From cspears2002 at yahoo.com Tue Aug 12 07:41:59 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 11 Aug 2008 22:41:59 -0700 (PDT) Subject: [Tutor] ecommerce.py Message-ID: <789878.94861.qm@web51607.mail.re2.yahoo.com> I am working on problem 13-11 from Core Python Programming (2nd Edition). For the problem, I am supposed to create the foundations of an e-commerce engine for a B2C business-to-consumer) retailer. I need to create a class that represents the customer called User, a class for items in inventory called Item, and a shopping cart class called Cart. I call my Item class Widget because I like the word. Multiple widgets can go in carts, and a User can have multiple Carts. Here is what I have written so far: #!/usr/bin/python class Widget(object): pass class Cart(object): def __init__(self,name): self.name = name print "Created " + self.name class User(object): def __init__(self,name="John Doe"): self.name = name print "Hello " + self.name + "!" self.cart_number = 0 self.cart_list = [] def make_cart(self,cart_name): cart = Cart(cart_name) self.cart_number = self.cart_number + 1 self.cart_list.append(cart.name) def carts_info(self): print "You have %d carts!" % self.cart_number for i, c in enumerate(self.cart_list): print "%d %s" % (i+1, c) if __name__ == '__main__': user_name = raw_input("Enter your name: ") user = User(user_name) print "You can " print "1) Create a cart" print "2) Buy a widget" print "3) List your carts" print "4) Quit" while True: while True: choice = raw_input("Pick an option: ") try: choice_int = int(choice) break except ValueError: print "Invalid choice!" print "Try again!" if choice_int == 1: cart_name = raw_input("Enter the name of your cart: ") user.make_cart(cart_name) elif choice_int == 2: print "I bought a widget." elif choice_int == 3: user.carts_info() elif choice_int == 4: print "Goodbye!" break else: print "Invalid Choice!" print "Try Again!" I am not sure how to handle putting Widgets into a Cart. Somehow, I need the user to be able to select the Cart he or she wants and then put Widgets in it. Any hints? Thanks! From unseeneasy at yahoo.com Tue Aug 12 07:48:09 2008 From: unseeneasy at yahoo.com (steve) Date: Mon, 11 Aug 2008 22:48:09 -0700 (PDT) Subject: [Tutor] hello.py: line 1: print: command not found Message-ID: <897289.59372.qm@web35301.mail.mud.yahoo.com> Hi In order to execute python script by fedora terminal ; insert #! /bin/env python as the first line in the script. Python scripts end with a file extension of .py, as indicated above. It is also possible in Unix to automatically launch the Python interpreter without explicitly invoking it by name from the command line. If you are using any Unix-flavored system, you can use the shell-launching ("sh-bang") first line of your program: #!/usr/local/bin/pythonThis may futher help Source Core Python Programming The file path, the part that follows the #!, is the full path location of the Python interpreter. As we mentioned before, it is usually installed in /usr/local/bin or /usr/bin. If not, be sure to get the exact pathname correct so that you can run your Python scripts. Pathnames that are not correct will result in the familiar Command not found error message. As a preferred alternative, many Unix systems have a command named env, installed in either /bin or /usr/bin, which will look for the Python interpreter in your path. If you have env, your startup line can be changed to something like this: #!/usr/bin/env python or, if your env is located in /bin, #!/bin/env python env is useful when you either do not know exactly where the Python executable is located, or if it changes location often, yet still remains available via your directory path. Once you add the proper startup directive to the beginning of your script, it becomes directly executable, and when invoked, loads the Python interpreter first, then runs your script. As we mentioned before, Python no longer has to be invoked explicitly from the command. You only need the script name: $ script.py -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080811/2ec04fa5/attachment.htm> From timothy.grant at gmail.com Tue Aug 12 08:18:41 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 11 Aug 2008 23:18:41 -0700 Subject: [Tutor] How to reference a wx.grid.Grid outside the methodinwhich it was created? In-Reply-To: <08A3FCE023ED4C65B4E54E25D4DEB005@laurenpc> References: <34880.69.16.140.5.1218471976.squirrel@www.protopc.com> <g7qhsf$2br$1@ger.gmane.org> <08A3FCE023ED4C65B4E54E25D4DEB005@laurenpc> Message-ID: <e775286d0808112318w107271d9ob5263cddd8f91aa1@mail.gmail.com> On Mon, Aug 11, 2008 at 10:40 PM, Lauren Snyder <lauren at protopc.com> wrote: > Will do! > > Thanks again, > Lauren :-) Let me just add a plug for the wx-python mailing list. it's a good place to learn if you're using wxpython. -- Stand Fast, tjg. [Timothy Grant] From daniel.yen at fortemall.com Tue Aug 12 05:53:13 2008 From: daniel.yen at fortemall.com (ypyean) Date: Mon, 11 Aug 2008 20:53:13 -0700 (PDT) Subject: [Tutor] Online Python teachers/tutors wanted Message-ID: <18937636.post@talk.nabble.com> ForteMall is looking for online Python teachers, instructors and tutors. You can teach worldwide online at your home. It is time to start your online teaching career on it. It is also a nice place where you can have second source of income generation. You can take it as part-time job and work at home first, or you can take it as full-time job for more freedom life. If you are interested, you can visit (http://www.fortemall.com) for more detail information. -- View this message in context: http://www.nabble.com/Online-Python-teachers-tutors-wanted-tp18937636p18937636.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Tue Aug 12 13:01:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Aug 2008 07:01:19 -0400 Subject: [Tutor] ecommerce.py In-Reply-To: <789878.94861.qm@web51607.mail.re2.yahoo.com> References: <789878.94861.qm@web51607.mail.re2.yahoo.com> Message-ID: <1c2a2c590808120401q1eb7eeaep889f840d432197b9@mail.gmail.com> On Tue, Aug 12, 2008 at 1:41 AM, Christopher Spears <cspears2002 at yahoo.com> wrote: > I am not sure how to handle putting Widgets into a Cart. Somehow, I need the user to be able to select the Cart he or she wants and then put Widgets in it. Any hints? You figured out how to put a Cart in a User, I guess you want something similar - a cart should have a list of widgets. Maybe the problem asks for it, but usually an online shop has just one cart per user and the cart is created for you when you ask to buy something. If you use that design it might be simpler. Kent From ptader at linuxscope.com Tue Aug 12 14:40:40 2008 From: ptader at linuxscope.com (Paul Tader) Date: Tue, 12 Aug 2008 07:40:40 -0500 (CDT) Subject: [Tutor] Easiest way to display HTML Message-ID: <49655.24.15.234.107.1218544840.squirrel@mail.linuxscope.com> I have a collection of python scripts that are written to be run from the command prompt. I now want to write the output (tables mostly) to a webpage using cron or as a cgi script. I've read about most web frameworks out there but many seem to be more than what I'm looking for. The closest I've seen is HTMLgen, but that project seems to be very quiet. In short, what would you use to quickly mark up your scripts simple output? Thanks, ptader From kent37 at tds.net Tue Aug 12 14:45:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Aug 2008 08:45:01 -0400 Subject: [Tutor] requests/responses from urllib2 In-Reply-To: <5FD78F0A-2FF2-4864-97FA-A3DE771DFFC1@ericabrahamsen.net> References: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> <1c2a2c590808110354k1a879a6dm4777d446ea972994@mail.gmail.com> <5FD78F0A-2FF2-4864-97FA-A3DE771DFFC1@ericabrahamsen.net> Message-ID: <1c2a2c590808120545m325737bdj876a13cbd328735f@mail.gmail.com> On Tue, Aug 12, 2008 at 7:27 AM, Eric Abrahamsen <eric at ericabrahamsen.net> wrote: > > On Aug 11, 2008, at 6:54 PM, Kent Johnson wrote: >> I'm not sure if you want to see the traffic coming in from your users, >> or the traffic from your server to the third-party server. I don't >> know what kind of interaction you want, either. > > I'd like to be able to see the response coming back from the third-party > server, and have lighttpd check its headers and either intercept it or allow > it back into the framework. Say if it's got a text content-type then let it > in to the framework, and if it's got an image content-type then ignore it or > throw it away. Rephrasing it this way makes it sound pretty unlikely. I > guess what I wanted was a better sense of how urllib2 uses a socket to make > the request, and how the response, on its way back to my server, finds that > socket. I thought that if the socket file was something that hung around > between requests, I might be able to configure lighttpd to 'listen in' on > that socket, and grab the response if it met certain criteria. But if that > were possible then urllib2 would raise an error, right? lighttpd will not see the traffic to the third-party server; the tp server is not making a request of lighttpd; your code is making a request of it. The response comes back on the same socket that was opened by the request; if you want to know how they match up you will have to learn about TCP/IP which is the underlying network protocol. This might help: http://www.amk.ca/python/howto/sockets/ If you want to filter the response according to the headers, you can do that in your code. The response object returned by urllib2 includes an info() method that gives access to the response headers. Kent PS Please Reply All to reply to the list. From alan.gauld at btinternet.com Tue Aug 12 17:37:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Aug 2008 16:37:48 +0100 Subject: [Tutor] Easiest way to display HTML References: <49655.24.15.234.107.1218544840.squirrel@mail.linuxscope.com> Message-ID: <g7sao9$vdl$1@ger.gmane.org> "Paul Tader" <ptader at linuxscope.com> wrote > The closest I've seen is HTMLgen, but that project seems to be very > quiet. > > In short, what would you use to quickly mark up your scripts simple > output? HTMLgen still works. There has been little activity because I guess there's not much more to do! Or maybe not many folks asking for more:-) But personally I tend to create HTML using either hard coded format strings in my code and string formatting title = "<h1>%s</h1>" print title % 'My page here' or using a templating system like Kid. If you are generating the HTML from a python script run from a con job then I'd guess the former will be sufficient for your needs. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Aug 12 20:36:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Aug 2008 14:36:07 -0400 Subject: [Tutor] Easiest way to display HTML In-Reply-To: <49655.24.15.234.107.1218544840.squirrel@mail.linuxscope.com> References: <49655.24.15.234.107.1218544840.squirrel@mail.linuxscope.com> Message-ID: <1c2a2c590808121136g3a3ba259o9ee2da1ad3b2aa96@mail.gmail.com> On Tue, Aug 12, 2008 at 8:40 AM, Paul Tader <ptader at linuxscope.com> wrote: > The closest I've seen is HTMLgen, but that project seems to be very quiet. > > In short, what would you use to quickly mark up your scripts simple output? Some other possibilities here: http://wiki.python.org/moin/Templating#head-aa4f37defbe454b2c08d4679c95987922d2bbc04 Kent From jaggojaggo at gmail.com Tue Aug 12 20:31:44 2008 From: jaggojaggo at gmail.com (Jaggo) Date: Tue, 12 Aug 2008 21:31:44 +0300 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> Message-ID: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Hello. I haven't much experience with programming. I'd like to point this question to programmers who write in editors other than the default PyWin32: Why do you use your editor rather than using Pywin? What feature has editor X got that PyWin hasn't? (That is, other than "My editor runs on unix / linux"; while that does count for something it is rather irrelevant to my current situation.) Thanks in advance, Omer. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080812/4e9776bc/attachment.htm> From Mike.Hansen at atmel.com Tue Aug 12 22:08:17 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 12 Aug 2008 14:08:17 -0600 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D033E776A@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Jaggo > Sent: Tuesday, August 12, 2008 12:32 PM > To: tutor at python.org > Subject: [Tutor] What has Editor X got that PyWin32 hasn't? > > Hello. > > > I haven't much experience with programming. > > I'd like to point this question to programmers who write in > editors other than the default PyWin32: > > Why do you use your editor rather than using Pywin? What > feature has editor X got that PyWin hasn't? > (That is, other than "My editor runs on unix / linux"; while > that does count for something it is rather irrelevant to my > current situation.) > > Thanks in advance, > Omer. Is that the editor that comes with Activestate's Python distribution for Windows? If so, I haven't used in a very long time. I switch between VIM and Komodo IDE. I don't remember the pythonwin editor having code completion for python, syntax highlighting for other languages(Perl? Ruby? HTML?), ftp, integration with your favorite source code control system, a spell checker, the ability to script it or record macros, an MP3 player, voice recognition, a Vulcan mind-meld programming link, .... oh... those last three are probably in emacs.. %-) Mike From steve at alchemy.com Tue Aug 12 22:09:42 2008 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 12 Aug 2008 13:09:42 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <48A1EE06.70606@alchemy.com> Jaggo wrote: > Why do you use your editor rather than using Pywin? What feature has editor > X got that PyWin hasn't? > (That is, other than "My editor runs on unix / linux"; while that does count > for something it is rather irrelevant to my current situation.) I use a different editor (in my case vim) because it has a lot of advanced editing features (regular expression searching and replacing, filtering ranges of text through commands, and a list of scores of other things) that don't exist in the simpler editors built into most IDEs like Pywin or IDLE. From flaxeater at gmail.com Tue Aug 12 22:50:41 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Tue, 12 Aug 2008 16:50:41 -0400 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <48A1EE06.70606@alchemy.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <48A1EE06.70606@alchemy.com> Message-ID: <584940990808121350m46f71a0pf7446bfc16f8d318@mail.gmail.com> Well I would imagine that many of the programmers here use emacs or vim. I use vim, however I've used komodo for python and I liked it a lot. However if you are going to program a great deal (I don't' know what your intentions are) then I recomend taking the 20-40 hour it takes to learn emacs or vim. These editors allow you to shovel around code like your a ditch digger, with cybernetic implants. Vim has code completion and it's very easy to use your keyboard to switch to specific tabs, instead of ctrl-tab,tab,tab,tab,tab,tab. It does have command completion though it requires you to tell it how to do so. Syntax highlighting and many other must haves for me. There is one thing that VIM and emacs have for them that many of the more GUI editors lack. That is terminal support that is equal to the GUI version. I do a lot of system administration just to get my programming tasks done and I often do not have physical access to the machine so I need to do it remotely. Which is a huge win for me. On Tue, Aug 12, 2008 at 4:09 PM, Steve Willoughby <steve at alchemy.com> wrote: > Jaggo wrote: >> >> Why do you use your editor rather than using Pywin? What feature has >> editor >> X got that PyWin hasn't? >> (That is, other than "My editor runs on unix / linux"; while that does >> count >> for something it is rather irrelevant to my current situation.) > > I use a different editor (in my case vim) because it has a lot of advanced > editing features (regular expression searching and replacing, filtering > ranges of text through commands, and a list of scores of other things) that > don't exist in the simpler editors built into most IDEs like Pywin or IDLE. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jfabiani at yolo.com Wed Aug 13 00:56:41 2008 From: jfabiani at yolo.com (johnf) Date: Tue, 12 Aug 2008 15:56:41 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <200808121556.41791.jfabiani@yolo.com> On Tuesday 12 August 2008 11:31:44 am Jaggo wrote: > Hello. > > I haven't much experience with programming. > > I'd like to point this question to programmers who write in editors other > than the default PyWin32: > > Why do you use your editor rather than using Pywin? What feature has editor > X got that PyWin hasn't? > (That is, other than "My editor runs on unix / linux"; while that does > count for something it is rather irrelevant to my current situation.) > > Thanks in advance, > Omer. I use wing. Wing does cost $ (but they have a freebie). So why am I willing to pay for the use of of editor when VIM, eclipse, and many others are available free of any cost. Because I use it on a daily basis and it is simple. I don't have to recall just how to get something done using a special command. I can write scripts, debug (has a very good debugger), code completion, provides project management. Etc... etc... The bottom line is I like it and I'm not alone there are a large number of pro's using wing. But you should fine out what you like by testing the editors. There is a large list of editors available including the latest from Netbeans. -- John Fabiani From cspears2002 at yahoo.com Wed Aug 13 01:54:56 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 12 Aug 2008 16:54:56 -0700 (PDT) Subject: [Tutor] ecommerce.py In-Reply-To: <1c2a2c590808120401q1eb7eeaep889f840d432197b9@mail.gmail.com> Message-ID: <906616.47489.qm@web51604.mail.re2.yahoo.com> Hey Everybody, I took Kent's advice and changed the design of the script. Tell me what you think! #!/usr/bin/python class Widget(object): def __init__(self,widget_number): self.widget_number = widget_number #print "Created Widget %d" % widget_number class Cart(object): def __init__(self,name): self.name = name print "Created " + self.name def add_widgets(self,number_widgets): for n in range(number_widgets): widget = Widget(n + 1) print "I put %d widgets in the cart!" % number_widgets class User(object): def __init__(self,name="John Doe"): self.name = name print "Hello " + self.name + "!" self.cart_number = 0 self.cart_list = [] self.cart_dict = {} def buy_widgets(self,cart_name,number_widgets): cart = Cart(cart_name) self.cart_number = self.cart_number + 1 self.cart_list.append(cart.name) cart.add_widgets(number_widgets) self.cart_dict[cart_name] = number_widgets def carts_info(self): print "You have %d carts!" % self.cart_number for i, c in enumerate(self.cart_list): print "%d) %s has %d widgets" % (i+1, c, self.cart_dict[c]) if __name__ == '__main__': user_name = raw_input("Enter your name: ") user = User(user_name) print "You can " print "1) Buy a widget" print "2) List your carts" print "3) Quit" while True: while True: choice = raw_input("Pick an option: ") try: choice_int = int(choice) break except ValueError: print "Invalid choice!" print "Try again!" if choice_int == 1: cart_name = raw_input("Enter the name of your cart: ") number_widgets = raw_input("How many widgets do you want? ") number_widgets_int = int(number_widgets) user.buy_widgets(cart_name,number_widgets_int) elif choice_int == 2: user.carts_info() elif choice_int == 3: print "Goodbye!" break else: print "Invalid Choice!" print "Try Again!" --- On Tue, 8/12/08, Kent Johnson <kent37 at tds.net> wrote: > From: Kent Johnson <kent37 at tds.net> > Subject: Re: [Tutor] ecommerce.py > To: cspears2002 at yahoo.com > Cc: tutor at python.org > Date: Tuesday, August 12, 2008, 4:01 AM > On Tue, Aug 12, 2008 at 1:41 AM, Christopher Spears > <cspears2002 at yahoo.com> wrote: > > I am not sure how to handle putting Widgets into a > Cart. Somehow, I need the user to be able to select the > Cart he or she wants and then put Widgets in it. Any hints? > > You figured out how to put a Cart in a User, I guess you > want > something similar - a cart should have a list of widgets. > > Maybe the problem asks for it, but usually an online shop > has just one > cart per user and the cart is created for you when you ask > to buy > something. If you use that design it might be simpler. > > Kent From alan.gauld at btinternet.com Wed Aug 13 02:11:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Aug 2008 01:11:57 +0100 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <g7t8sb$5d7$1@ger.gmane.org> "Jaggo" <jaggojaggo at gmail.com> wrote > I haven't much experience with programming. > > Why do you use your editor rather than using Pywin? Thats one of the most contentious issues in programming. Coders love their editors like other people love their pets! > What feature has editor X got that PyWin hasn't? PyWin is a pretty basic editor. Although its much better than Notepad and indeed better than IDLE it is still a long way short of the power that heavyweight editors like vim, emacs, eclipse and so forth have. I use Pythonwin for most of my short programming tasks (with occasional forays into other tools like PyCrust and SPE) but for serious programming I use vim. Why? 1) Split screen editing of single or multiple files 2) the ability to perform any edit command without taking my hands from the keybioard home positioon - very important for touch typists! (actually its a lie, I'm not a touch typist, but many coders are and its a big deal for them!) 3) integration with the OS. Piping bufrers through the shell, running shell commands into a buffer, use of grep to find and navigate to files etc 4) navigation around code using tags. GoTo Tag and autoloading a file is great. 5) macros. Being able to easily record a keyboard macros to automate repetitive tasks is fabulous 6) command repeat compbined with next search. Use the n key to go to the next search location and '.' to repeat the last editing command at that point is super fast. 7) syntax highlighting in multiple languages not just python means I can load SQL files, batch files, HTML files etc etc and they are all syntax coloured (Note that scintilla the editing widget used in Pythonwin does this but pythonwin doesn't use it!) 8) intuitive commands. Once you figure out the arcane logic used in the vi command set you can pretty much guess what any given command will be. 9) built in help system for the editor. The pythonwin help system is more interested in the COM programming etc. Its nowhere near as full as the vim help Against that, pythonwin gains from: 1) easy to learn 2) familiar style to other windows apps 3) better debugger than vim 4) better code browser than vim 5) better collapsing mode than vim 6) better tooltip help So as a beginner I'd stick to Pythonwin. Once you have got the language under your belt you can start lokintg at power editors. I'd probably start with Eclipse. It is a more modern design than vim but packed with power tools and lots of add-in plugins. It may not be quite as fast in pure productivity terms but its a lot less intimidating than either vim or emacs. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Wed Aug 13 06:17:14 2008 From: rdm at rcblue.com (Dick Moores) Date: Tue, 12 Aug 2008 21:17:14 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <g7t8sb$5d7$1@ger.gmane.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> Message-ID: <20080813041728.2E8DC1E4003@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080812/636b2f13/attachment.htm> From xboxmuncher at gmail.com Wed Aug 13 06:45:44 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Wed, 13 Aug 2008 00:45:44 -0400 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? Message-ID: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> Yes I think python is great in its simplicity in typing code but not in its absence of curly brackets to surround code blocks. Personally, it helps me visually see the code blocks as well as saves me constant pain when the compiler complains about broken/missing indents in the code.* I think it would be great if there was an editor for python or a plugin for an existing program to be able to use curly brackets { } when defining code blocks, and then maybe with a push of a button it can convert the curly bracket style code that ignores indents to the indent sensitive code that the python compiler wants. *It would save me a lot of headache in the way too many times I'm constantly trying to hunt down indentation problems in code (usually other people's code). I tried getting different editors with "auto-identing" as it is listed in the recommend python editors in the python website. However, these don't suffice in fixing most indenation problems... They sometimes even make it worse! Even visually a lot of people write their lines like this: def funcName(arg): bla bla bla more content of function if (this == that) do this Simple indentation errors can be a nightmare in determining whether if statements and other code blocks are inside of another code block or not.... when all that seperates them is a single bad indent, which could be the error you're looking for, or what it that way in the begg! *So if you know of a plugin for a python editor, let me know. :)* Also, another idea is to edit the compiler somehow or create soem kind of process/script that all scripts with teh curly brackets will get removed before being processed... I'd settle for this solution as well if it exists... I"m sure I'm not the only one that has contemplated a curly bracket workaround for python before. :) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/aee63882/attachment.htm> From dextrous85 at gmail.com Wed Aug 13 07:42:00 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Wed, 13 Aug 2008 11:12:00 +0530 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> Message-ID: <5487b3060808122242m4235b3c7rc445d4a0a9fb78b2@mail.gmail.com> try typing this on your python shell : *from __future__ import braces* check the output:* SyntaxError: not a chance (<pyshell#0>, line 1)* On Wed, Aug 13, 2008 at 10:15 AM, xbmuncher <xboxmuncher at gmail.com> wrote: > Yes I think python is great in its simplicity in typing code but not in its > absence of curly brackets to surround code blocks. Personally, it helps me > visually see the code blocks as well as saves me constant pain when the > compiler complains about broken/missing indents in the code.* I think it > would be great if there was an editor for python or a plugin for an existing > program to be able to use curly brackets { } when defining code blocks, and > then maybe with a push of a button it can convert the curly bracket style > code that ignores indents to the indent sensitive code that the python > compiler wants. *It would save me a lot of headache in the way too many > times I'm constantly trying to hunt down indentation problems in code > (usually other people's code). I tried getting different editors with > "auto-identing" as it is listed in the recommend python editors in the > python website. However, these don't suffice in fixing most indenation > problems... They sometimes even make it worse! > > Even visually a lot of people write their lines like this: > def funcName(arg): > bla bla bla > more content of function > if (this == that) > do this > > Simple indentation errors can be a nightmare in determining whether if > statements and other code blocks are inside of another code block or not.... > when all that seperates them is a single bad indent, which could be the > error you're looking for, or what it that way in the begg! > > > *So if you know of a plugin for a python editor, let me know. :)* > Also, another idea is to edit the compiler somehow or create soem kind of > process/script that all scripts with teh curly brackets will get removed > before being processed... I'd settle for this solution as well if it > exists... > > I"m sure I'm not the only one that has contemplated a curly bracket > workaround for python before. :) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/25be1701/attachment-0001.htm> From alan.gauld at btinternet.com Wed Aug 13 09:41:25 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Aug 2008 08:41:25 +0100 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com><515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com><g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> Message-ID: <g7u374$v46$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > You've got me wanting to take a look at vim for Windows. > I just downloaded the "Self-installing executable gvim##.exe" > which is listed on < http://www.vim.org/download.php#pc>. > Is this the sort of vim you're talking about? Yes that's the one. I'm on v6.3 but I think the latest version is up to 7.x? However I tend not to use the newest features so 6.3 meets my needs. Alan G. From alan.gauld at btinternet.com Wed Aug 13 09:55:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Aug 2008 08:55:26 +0100 Subject: [Tutor] Is there python editor or plugin for a python editor forcurly brackets around code blocks? References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> Message-ID: <g7u41c$1q5$1@ger.gmane.org> "xbmuncher" <xboxmuncher at gmail.com> wrote > visually see the code blocks as well as saves me constant pain when > the > compiler complains about broken/missing indents in the code.* Have you tried tabnanny that will fix up mixtures of tabs and spaces - which is the most common cause of indentationn errors in my experience Personally I haven't had an indentation error in months. I just get used to only using spaces. > would be great if there was an editor for python or a plugin for an > existing > program to be able to use curly brackets { } when defining code > blocks, and > then maybe with a push of a button it can convert the curly bracket > style > code that ignores indents to the indent sensitive code that the > python > compiler wants. There is a unix program called indent that does the indentation bit, you would need to modify it to remove the braces (and of course keep the braces on dictionary definitions!) > times I'm constantly trying to hunt down indentation problems in > code > (usually other people's code). Really? Then I assume it didn't work in the first place? Once code works you shouldn't get indentation errors unless you modify it. (And thats where mixing tabs and spaces becomes an issue and tabnanny can help.) > Even visually a lot of people write their lines like this: > def funcName(arg): > bla bla bla > more content of function > if (this == that) > do this Thats would be an errror if the condition is supposed to be inside the function. So nobody should be writing code like that! :-) We often see that on the mailing list but its usually the result of email reformatting in transit. > Simple indentation errors can be a nightmare in determining whether > if > statements and other code blocks are inside of another code block or > not.... > when all that seperates them is a single bad indent, which could be > the > error you're looking for, or what it that way in the begg! I agree it can be frustrating when dealing with other peoples faulty code. I have had to struggle with that. But then, I've had to struggle with that in C too because of the inconsistency of styles in C bracing - single line blocks don;t need it, multi lines do. And the indentation of braces is a huge cause for debate if (foo) { code } if (foo) { code } if (foo) { code } etc... When different coders mix styles then working out whats intended is at least as diffixcult as in Python IMHO. > Also, another idea is to edit the compiler somehow or create > soem kind of process/script that all scripts with teh curly > brackets will get removed before being processed... Good luck but I don;t think you'd have a chance of getting it accepted officially. Most python users, me included, love the absence of block markers! I'd even like to get rid of the colon! Alan G. From dextrous85 at gmail.com Wed Aug 13 10:10:49 2008 From: dextrous85 at gmail.com (vishwajeet singh) Date: Wed, 13 Aug 2008 13:40:49 +0530 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <g7u374$v46$1@ger.gmane.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> Message-ID: <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> I use pydev eclipse plugin for python and it saves me alot time. Packages and modules can be maintained pretty well and if error is in some dependent file I dont have to go to that folder to open it eclipse does it for me. Integration with subversion and JIRA also help me to work in a better way. On Wed, Aug 13, 2008 at 1:11 PM, Alan Gauld <alan.gauld at btinternet.com>wrote: > > "Dick Moores" <rdm at rcblue.com> wrote > >> You've got me wanting to take a look at vim for Windows. I just downloaded >> the "Self-installing executable gvim##.exe" which is listed on < >> http://www.vim.org/download.php#pc>. Is this the sort of vim you're >> talking about? >> > > Yes that's the one. I'm on v6.3 but I think the latest version is > up to 7.x? However I tend not to use the newest features so 6.3 meets my > needs. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/351a8487/attachment.htm> From cfuller084 at thinkingplanet.net Wed Aug 13 10:23:28 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 13 Aug 2008 03:23:28 -0500 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> Message-ID: <200808130323.28861.cfuller084@thinkingplanet.net> Some clarifications w.r.t. indentation and Python: http://www.secnetix.de/olli/Python/block_indentation.hawk It's just a joke, really: http://timhatch.com/projects/pybraces/ Turnabout is fair play! http://blog.micropledge.com/2007/09/nobraces/ Also, pindent.py in the Tools/scripts directory of your Python distribution will produce correctly indented scripts if the blocks are designated with a "#end" line. But seriously, you don't want to go creating a separate class of source file. It'll be harder for you and the other programmers to context switch when working with code that uses the standard style, will confuse others who won't know what to do with your code, adds overhead to the compiling, will break when somebody tries to run it under the standard environment, could clutter up your development directories, depending on the implementation, etc. Here's a thread from 1999 on the Python mailing list that discusses the issue: http://mail.python.org/pipermail/python-list/1999-June/004450.html There's another script towards the end that might even do what you want, but you might want to read what they have to say first :) Cheers From lie.1296 at gmail.com Wed Aug 13 11:56:19 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 13 Aug 2008 16:56:19 +0700 Subject: [Tutor] Unable to catch exception In-Reply-To: <mailman.14041.1218406731.920.tutor@python.org> References: <mailman.14041.1218406731.920.tutor@python.org> Message-ID: <1218621379.6337.2.camel@lieryan-laptop> > Message: 7 > Date: Sun, 10 Aug 2008 18:16:38 -0400 > From: James <jtp at nc.rr.com> > Subject: Re: [Tutor] Unable to catch exception > To: "Kent Johnson" <kent37 at tds.net> > Cc: tutor at python.org > Message-ID: > <e107b4ff0808101516y59b52dafweb6d7a4eb9cdc0cc at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Kent, > > I'm not importing BadStatusLine. I'm only importing mechanize, which > downloads a page repeatedly. From time to time a BadStatusLine > exception is raised. I'm unsure how to go about catching it. > > Thoughts? Did you say you used threads to download the page (i.e. you used thread or threading module? If so, then move the exception handler INSIDE the thread or threading code because exception handler only catch exception in its own thread. so instead of this: (untested) #!/usr/bin/env python import time from threading import Thread class MyThread(Thread): def __init__(self,bignum): Thread.__init__(self) def run(self): while True: if someCondition: raise AnError if __name__=="__main__": try: MyThread().start() except AnError: print 'Got Error' do this instead: #!/usr/bin/env python import time from threading import Thread class MyThread(Thread): def __init__(self,bignum): Thread.__init__(self) def run(self): try: while True: if someCondition: raise AnError except AnError: print 'Got Error' if __name__=="__main__": MyThread().start() > > -j > > On Sun, Aug 10, 2008 at 1:54 PM, Kent Johnson <kent37 at tds.net> wrote: > > On Sat, Aug 9, 2008 at 12:28 PM, James <jtp at nc.rr.com> wrote: > >> All, > >> > >> I'm having a rather strange problem that I'm hoping someone can > shed > >> some light on. I'm trying to catch a BadStatusLine exception raised > by > >> the httplib library. > >> The error only happens once every blue moon, but to avoid a crash I > >> setup a try/catch. > >> > >> try: > >> <download page code here> > >> catch BadStatusLine: > >> print "yuck!" > >> > >> However, somehow the thread that this code is in still raised a > >> BadStatusLine exception and the thread stopped cold. > > > > How did you import BadStatusLine? > > > > One strange gotcha about except statements is that the except clause > > is not evaluated until an exception is raised, so you can have an > > invalid name and you won't know it. For example this runs fine, even > > though foo is not defined: > > In [1]: try: > > ...: 1 > > ...: except foo: > > ...: pass > > ...: > > Out[1]: 1 > > > > OTOH if an exception is raised it causes a NameError: > > In [2]: try: > > ...: 1/0 > > ...: except foo: > > ...: pass > > ...: > > > --------------------------------------------------------------------------- > > <type 'exceptions.NameError'> Traceback (most recent > call last) > > > > /Users/kent/<ipython console> in <module>() > > > > <type 'exceptions.NameError'>: name 'foo' is not defined > > > > Kent > > > From lie.1296 at gmail.com Wed Aug 13 12:06:03 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 13 Aug 2008 17:06:03 +0700 Subject: [Tutor] Tutor Digest, Vol 54, Issue 43 In-Reply-To: <mailman.15027.1218571793.920.tutor@python.org> References: <mailman.15027.1218571793.920.tutor@python.org> Message-ID: <1218621963.6337.6.camel@lieryan-laptop> > Message: 3 > Date: Tue, 12 Aug 2008 07:40:40 -0500 (CDT) > From: "Paul Tader" <ptader at linuxscope.com> > Subject: [Tutor] Easiest way to display HTML > To: tutor at python.org > Message-ID: > <49655.24.15.234.107.1218544840.squirrel at mail.linuxscope.com> > Content-Type: text/plain;charset=iso-8859-1 > > I have a collection of python scripts that are written to be run from > the > command prompt. I now want to write the output (tables mostly) to a > webpage using cron or as a cgi script. I've read about most web > frameworks out there but many seem to be more than what I'm looking > for. > The closest I've seen is HTMLgen, but that project seems to be very > quiet. > > In short, what would you use to quickly mark up your scripts simple > output? > > Thanks, > ptader You know, the reason why text-based format is great is because you don't need any complication if you don't want to, web frameworks, templating system, HTMLgen are great for complex pages where every single thing seems so complex, but writing to a file (or redirecting stdout to a file, then do a print) is sufficient for many simple applications. From marc.tompkins at gmail.com Wed Aug 13 12:06:54 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 13 Aug 2008 03:06:54 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> Message-ID: <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> On Wed, Aug 13, 2008 at 1:10 AM, vishwajeet singh <dextrous85 at gmail.com>wrote: > I use pydev eclipse plugin for python and it saves me alot time. > Packages and modules can be maintained pretty well and if error is in some > dependent file I dont have to go to that folder to open it eclipse does it > for me. > Integration with subversion and JIRA also help me to work in a better way. > I tried pydev for about a week - I'd started using SPE (Stani's Python Editor, http://pythonide.stani.be/) after about five days of Python, and was feeling a bit guilty that I was still using "training wheels"... Damn, that week sucked. More than ever, I pity full-time Java coders and the monstrosities they have to put up with. I tried Wing for a few days; meh. I ran back to SPE as fast as I could, and have only flirted with vim since. (Vi and vim have been New Year's resolutions of mine for about twenty years now. Everybody who uses vim raves about its greatness, but it took me less time to write my first useful Python program than it did to figure out how to open, change, and save a file in vim. OK, I exaggerate a BIT...) Good Things about SPE: - Tabbed editing - "Output" pane, plus separate terminal pane for quickies - Click on any line in an error traceback to jump to the offending line. Any file that isn't already, opens automatically when you click it. - Left pane toggles between: - Code outline; specially formatted comment lines appear as section headers in outline - Todo list - Index - Notes - TabNanny compiling checker (finds errors that work OK now, but might bite you later) - File browser - Collapse/expand blocks of code for compact viewing - Syntax highlighting (of course!) - Code completion, inline help with function/method parameters - Excellent integration with WinPdb debugger - Excellent integration with PyDoc documentation generation/formatting/printing - TabNanny Not-so-Good Things: - Integrated subversion would be a nice plus. (Actually, I use Bazaar anyway.) - Programs you start from inside the IDE run as children of SPE, so inherit SPE's environment. Not really a Bad Thing, just something to be aware of - if you make changes to the environment, and want your program to see them, run it from outside SPE or else restart SPE (which takes a fraction of the time it takes to restart Eclipse, by the way.) One Of These Days, I'm sure I'll get around to learning vim, and I'll wonder what I ever did without it. Until then, I'm using SPE. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/e7e01e32/attachment.htm> From rdm at rcblue.com Wed Aug 13 13:15:38 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 04:15:38 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.co m> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> Message-ID: <20080813111551.646BC1E4016@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/23aaf767/attachment.htm> From srilyk at gmail.com Wed Aug 13 13:22:40 2008 From: srilyk at gmail.com (W W) Date: Wed, 13 Aug 2008 06:22:40 -0500 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080813041728.2E8DC1E4003@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> Message-ID: <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> On Tue, Aug 12, 2008 at 11:17 PM, Dick Moores <rdm at rcblue.com> wrote: > At 05:11 PM 8/12/2008, Alan Gauld wrote: > > I use Pythonwin for most of my short programming tasks > (with occasional forays into other tools like PyCrust and SPE) but for > serious programming I use vim. Why? > > > Alan, > > I used vi/vim a lot years ago in the shell account days. You've got me > wanting to take a look at vim for Windows. I just downloaded the "*Self-installing > executable* gvim##.exe" which is listed on <http://www.vim.org/download.php#pc>. > Is this the sort of vim you're talking about? > Make sure you run vimtutor ;) And read this: http://www.moolenaar.net/habits.html and then you will most likely never go back - at least I haven't/don't. I feel crippled when I program in anything without the power of vi/vim, even though I can probably almost match my speed with some of the ctrl+ and shift+ hotkeys in most editors. Still, for all of the reasons that other people mention, and my biggest reason is that I can select and move around massive amounts of code without moving my hands much. If I want to delete 10 lines of code, 10dd does it. If I want to change a word, cw. If I want to change several words, the number of words followed by cw. and I find the autocomplete WAY useful. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/bc6fae8f/attachment.htm> From rdm at rcblue.com Wed Aug 13 14:31:03 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 05:31:03 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.co m> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> Message-ID: <20080813123116.ADE181E4004@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/61bba4d8/attachment.htm> From marc.tompkins at gmail.com Wed Aug 13 14:33:07 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 13 Aug 2008 05:33:07 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080813111551.646BC1E4016@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> <20080813111551.646BC1E4016@bag.python.org> Message-ID: <40af687b0808130533x935090o2ac0b20f11282fd7@mail.gmail.com> On Wed, Aug 13, 2008 at 4:15 AM, Dick Moores <rdm at rcblue.com> wrote: > I've marked your list with *** for yes; ### for no; ??? for not sure or not > sure what you mean. > At 03:06 AM 8/13/2008, Marc Tompkins wrote: > > - Todo list ??? But TODO's in code are flagged > > I'd never used it before, but I just tried it: I inserted "# Todo: stuff" on line 24 of my program and it appeared in the Todo list. So the same, I guess. > - Index ??? If you mean a browser of functions, classes, and variables, > then yes. > > Yup. > - TabNanny compiling checker (finds errors that work OK now, but might > bite you later) ??? > > I don't remember now where I saw the name "TabNanny" - I just ran the checker, and it didn't say that (maybe it was in the first version of SPE I used.) Looking at menu, I see that it's PyChecker. I've never compared head-to-head with pylint, but it finds the same stuff that lint would > but indentation problems are taken care of. > > Now, that gets a "????" from me. SPE lets you set whether the tab key should insert tabs or spaces, and if (as is recommended) you chose spaces, then how many. Also whether to automatically convert tabs to spaces in files that you open. If that's what you mean... well, I wouldn't write Python in an editor that didn't do that. (OK, I do use Notepad, or joe, or what have you, in a pinch. But not for any longer than I have to.) If you mean, does it read my mind and realize that when I wrote if something: this that the other I really meant if something: this that the other then no, it's not that smart. Damn. > > I didn't know SPE had come so far. However, Ulipad has most of what you > list, and more. > > Some more features are: > Code snippets window > That's what I use the Notes area for. > FTP window > Now, I can see how that would be useful, but I love me some FileZilla. I'm not sure I'd use an FTP window in my editor unless it was as good... > > can group files in "sessions" > They're called "Workspaces" in SPE > > "live" regex > SPE has Kiki, which I've never tried - I usually muck around in the Terminal area and cut-and-paste when my regex is working. > > search and replace > Well, yeah... I thought that one was kind of obvious; even IDLE has that. > > search in files > Yup. > > syntax checker > SPE shows a warning when you open any of (, {, [, ''', or """, and it sticks around till everything matches. Improperly continued lines, bad indentation (AHA! That's what you meant - the kind of indentation error that would blow up. Yeah, that's covered.) > > spell check > How does that work? I generally use camelCased names that would fail a spellcheck anyway, and if I misspell any Python keywords then I get a nice easy error message. > > pylint > As before - PyChecker. No idea of the relative merits. > > svn support > Ah well. > > a great many keybindings, mostly for the editor > Not a clue - not something I've been curious about... > > And last but not least, a developer who is quick to respond to email, or to > posts on the Ulipad mailing list. > I've never tried - I liked it, an update came out, I liked it even better - but a quick look at the lists seems promising, and for what it's worth he's frequently in the wxpython groups. To me, the best customer service is the kind you never need to use (not saying bad things don't happen, just that they haven't to me. Yet. Knock on wood.) I don't mean to be such an evangelist for it, but it seemed I'd left a few things out. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/91ed5c65/attachment-0001.htm> From Jaggojaggo+Py at gmail.com Wed Aug 13 15:14:52 2008 From: Jaggojaggo+Py at gmail.com (OmerT) Date: Wed, 13 Aug 2008 16:14:52 +0300 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? Message-ID: <515008f10808130614i33b8bf7al91c649a8b8f9202e@mail.gmail.com> To sum things up, Thank you, Hansen, Mike Steve Willoughby Chad Crabtree johnf Alan Gauld Dick Moores vishwajeet singh Marc Tompkins I reckon I'll give SPE a chance at the moment, and add vim to my ever growing list of things to try out once and when I get bored. From srilyk at gmail.com Wed Aug 13 16:04:40 2008 From: srilyk at gmail.com (W W) Date: Wed, 13 Aug 2008 09:04:40 -0500 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080813123116.ADE181E4004@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> <20080813123116.ADE181E4004@bag.python.org> Message-ID: <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> On Wed, Aug 13, 2008 at 7:31 AM, Dick Moores <rdm at rcblue.com> wrote: > <snip> > > And read this: http://www.moolenaar.net/habits.html > > > Hey, that looks very useful! Thanks. > > How about the O'Reilly book? <http://www.bestbookdeal.com/book/detail/059652983X/ > > > I've never read it, but looking at the summary it appears to give you the power and knowledge to become a vi/vim god... My current knowledge of vi/vim is probably maybe about 1% of what I could possibly know and utilize. For instance, I currently rely on other people to write my syntax files (the ones that govern highlighting, indention, et al). The list of commands I use could probably fit on a 3x5 notecard if you wrote small enough. But really it's enough for the casual and educational (read: my c++ class at the University of Central Arkansas) coding that I do. And I find it quicker (as in I'm able to edit and create more lines of code), more powerful (its features are more versatile and customizable), and more comfortable (I'm not constantly moving my hands around. They more or less stay stationary. I don't move back & forth to the mouse, I'm not constanly pushing ctrl, pg up/dn, home/end/del) than any other editor I've used. I've used note/wordpad, the microsoft visual studio editors, and IDLE and the ActiveState python editor. Once you're done with the vimtutor, and if(when ;) ) you find you enjoy vim, if you feel that you want to be able to do insane things, or you just wish you had a feature that was available in some other IDE, I'd bet that book is a good source. If you're just the average joe coder, my guess is that you'll be able to find all the information you want/need out on the web in various places. > > Still, for all of the reasons that other people mention, and my biggest > reason is that I can select and move around massive amounts of code without > moving my hands much. If I want to delete 10 lines of code, 10dd does it. If > I want to change a word, cw. If I want to change several words, the number > of words followed by cw. > > and I find the autocomplete WAY useful. > > and then you will most likely never go back - at least I haven't/don't. I > feel crippled when I program in anything without the power of vi/vim, even > though I can probably almost match my speed with some of the ctrl+ and > shift+ hotkeys in most editors. > > Is it better than in other editors? > The autocomplete, or vi/vim? Autocomplete is probably as good as most other editors. As you're typing, if you want autocomplete you push ctrl+n and it pops down a list of available matches. You push ctrl+n to cycle through the matches, and then either hit enter or continue typing. As far as vi/vim being better than other editors, well that depends on your personal preference and experience, but if you're a touch typist, prefer to use the keyboard, and hate wasting motions and extra keystrokes... vi/vim is probably for you. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/330a806e/attachment.htm> From rdm at rcblue.com Wed Aug 13 16:42:38 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 07:42:38 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.co m> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> <20080813123116.ADE181E4004@bag.python.org> <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> Message-ID: <20080813144253.7433E1E400D@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/1cb6c5ff/attachment.htm> From rdm at rcblue.com Wed Aug 13 16:42:38 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 07:42:38 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.co m> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> <20080813123116.ADE181E4004@bag.python.org> <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> Message-ID: <20080813144253.B55111E4021@bag.python.org> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/8813755f/attachment.htm> From srilyk at gmail.com Wed Aug 13 16:58:52 2008 From: srilyk at gmail.com (W W) Date: Wed, 13 Aug 2008 09:58:52 -0500 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080813144253.7433E1E400D@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> <20080813123116.ADE181E4004@bag.python.org> <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> <20080813144253.7433E1E400D@bag.python.org> Message-ID: <333efb450808130758g6d99fcb3kcb57b9666a1e20f4@mail.gmail.com> On Wed, Aug 13, 2008 at 9:42 AM, Dick Moores <rdm at rcblue.com> wrote: > > Since downloading vim 7.2 yesterday, I've had some trouble distinguishing > vim and gvim (both were included). Can you help me out? gvim is GUI-vim, I > think. Isn't that what I want to learn? Is gvim a cut-down version of vim, > but enables you to use your mouse ( :set mouse=a)? > As far as I know/have used, gvim is simply vim, but for lack of a better comparison, in its own terminal. The same thing you would have if you were to type "vim" at the command line. Honestly, the only thing I know how to do with the mouse in gvim is paste (middle click in linux). Or access the menus. That's one of the main reasons I /use/ vim - so I don't have to touch the mouse :) As far as any keyboard commands that I use, I've not seen any difference between vim, vi, and gvim. The main difference is syntax highlighting. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/dae6bcad/attachment-0001.htm> From rdm at rcblue.com Wed Aug 13 17:09:25 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 08:09:25 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <333efb450808130758g6d99fcb3kcb57b9666a1e20f4@mail.gmail.co m> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> <20080813123116.ADE181E4004@bag.python.org> <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> <20080813144253.7433E1E400D@bag.python.org> <333efb450808130758g6d99fcb3kcb57b9666a1e20f4@mail.gmail.com> Message-ID: <20080813150938.93CBB1E401C@bag.python.org> At 07:58 AM 8/13/2008, W W wrote: >As far as any keyboard commands that I use, I've not seen any >difference between vim, vi, and gvim. The main difference is syntax >highlighting. Uh, oh. What's the difference between syntax highlighting in vim and in gvim? Thanks, Dick From rdm at rcblue.com Wed Aug 13 17:35:16 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 08:35:16 -0700 Subject: [Tutor] Python 2 green arrows up for August! Message-ID: <20080813153527.BB8561E4004@bag.python.org> <http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html> Dick Moores From muchanek at gmail.com Wed Aug 13 17:35:36 2008 From: muchanek at gmail.com (kinuthiA muchanE) Date: Wed, 13 Aug 2008 18:35:36 +0300 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <mailman.15566.1218639544.920.tutor@python.org> References: <mailman.15566.1218639544.920.tutor@python.org> Message-ID: <1218641736.5782.19.camel@www.kinuthia.com> On Wed, 2008-08-13 at 16:59 +0200, tutor-request at python.org wrote: > > Message: 5 > Date: Wed, 13 Aug 2008 09:58:52 -0500 > From: "W W" <srilyk at gmail.com> > Subject: Re: [Tutor] What has Editor X got that PyWin32 hasn't? > To: "Dick Moores" <rdm at rcblue.com> > Cc: Python Tutor List <tutor at python.org> > Message-ID: > <333efb450808130758g6d99fcb3kcb57b9666a1e20f4 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Wed, Aug 13, 2008 at 9:42 AM, Dick Moores <rdm at rcblue.com> wrote: > > > > > Since downloading vim 7.2 yesterday, I've had some trouble > distinguishing > > vim and gvim (both were included). Can you help me out? gvim is > GUI-vim, I > > think. Isn't that what I want to learn? Is gvim a cut-down version > of vim, > > but enables you to use your mouse ( :set mouse=a)? You can subscribe to vim mailing list by sending a blank email to vim-subscribe at vim.org. It is very friendly even for beginners, Bram Moolenaar, also gets to answer your questions sometimes! ;) > > > > As far as I know/have used, gvim is simply vim, but for lack of a > better > comparison, in its own terminal. The same thing you would have if you > were > to type "vim" at the command line. > > Honestly, the only thing I know how to do with the mouse in gvim is > paste > (middle click in linux). Or access the menus. That's one of the main > reasons > I /use/ vim - so I don't have to touch the mouse :) > > As far as any keyboard commands that I use, I've not seen any > difference > between vim, vi, and gvim. The main difference is syntax highlighting. > > -Wayne > > > From alan.gauld at btinternet.com Wed Aug 13 17:38:18 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 13 Aug 2008 15:38:18 +0000 (GMT) Subject: [Tutor] What has Editor X got that PyWin32 hasn't? Message-ID: <71240.45390.qm@web86709.mail.ukl.yahoo.com> > Everybody who uses vim raves about its greatness, but it > took me less time to write my first useful Python program > than it did to figure out how to open, change, and save a > file in vim. OK, I exaggerate a BIT...) But not much. - The point about vi/vim is that it is written for power users. It makes no compromises for newbies. As such it has one of the steepest learning curves of any editir. But once you grasp the concepts it is one of(if not the) fasyest text editors around. Everything is designed to minimise typing for expert users- on the basis that you will spend far more time using it as an expert than you will becoming an expert. My first experience of vi was on the OS/9 real-time OS at uni. I had no alternative editor so I had to learn it (it was called scred = scvreen editor - on OS/9!) but I hated it after Turbo Pascal! then at work we moved fopm Vax to unix and I came across vi again. but this time surrounded by ex unix hackers who showed me its mysteries. More importantly they introduced me to tutvi (aka vitutor) which was where I had the flash of light that showed the logic in the keystrokes and in the modal way of working. I used vi/emacs equally on *nix systems ever since (and even ex sometimes - ex is the line mode of vi! - think edlin on DOS... When I moved to PC I found that emacs didn't seem to work so well on Windows so I stopped using it, but vim (gvim) was as good as ever! On the subject of eclipse, i tried it, and am now having to use it at work, and it was nice but slowwwwwww. Now I have a much faster PC I might try pydev again. Anyone know how to get a >>> prompt in eclipse? BTW One final option that i really like as a vim alternative for newbies is Scite. Its a more powerful version of the Pythonwin editor so everything you know from pythonwin works but it also does a zillion other languages plus has tabbed editing. Plus its very small and works from a flash drive so is easy to carry around. HTH, Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/fe23daca/attachment.htm> From alan.gauld at btinternet.com Wed Aug 13 17:50:28 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 13 Aug 2008 15:50:28 +0000 (GMT) Subject: [Tutor] What has Editor X got that PyWin32 hasn't? Message-ID: <546516.70513.qm@web86703.mail.ukl.yahoo.com> > If I want to delete 10 lines of code, 10dd does it. > If I want to change a word, cw. If I want to change > several words, the number of words followed by cw. Yes thats what I mean about consistency. 10dd - delete 10 lines 10cc - change10 lines 10yy - yank(copy) 10 lines etc... I rarely use the numbersthough becase the magic feature for me is the range commands. /fromstr/,/tostring/<cmd> applies cmd to the range of lines containing fromstr to the next line containing tostring And cmd can be almost any editing command. similarly you can apply commands to only those lines containing a given string. Also rectangular mode is great for messing with comments (almost essential in assembler code!) etc etc etc.... However I'll stop here because its got little to do with python and the vim advocacy pages have more than enough of this kind of promo material :-) Although of course you can get aversion of vim that uses python as its macro language! (But actually I don't use it) Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/38161c39/attachment.htm> From srilyk at gmail.com Wed Aug 13 17:52:17 2008 From: srilyk at gmail.com (W W) Date: Wed, 13 Aug 2008 10:52:17 -0500 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080813150938.93CBB1E401C@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com> <20080813123116.ADE181E4004@bag.python.org> <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> <20080813144253.7433E1E400D@bag.python.org> <333efb450808130758g6d99fcb3kcb57b9666a1e20f4@mail.gmail.com> <20080813150938.93CBB1E401C@bag.python.org> Message-ID: <333efb450808130852k4809b982veddd7fe99c2e6639@mail.gmail.com> On Wed, Aug 13, 2008 at 10:09 AM, Dick Moores <rdm at rcblue.com> wrote: > At 07:58 AM 8/13/2008, W W wrote: > >> As far as any keyboard commands that I use, I've not seen any difference >> between vim, vi, and gvim. The main difference is syntax highlighting. >> > > Uh, oh. What's the difference between syntax highlighting in vim and in > gvim? > > Ah, pardon me. That should be vi, and vim/gvim. IIRC, vi doesn't do syntax highlighting. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/d6191b3a/attachment.htm> From eric at ericabrahamsen.net Wed Aug 13 19:50:04 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Thu, 14 Aug 2008 01:50:04 +0800 Subject: [Tutor] requests/responses from urllib2 In-Reply-To: <1c2a2c590808120545m325737bdj876a13cbd328735f@mail.gmail.com> References: <877691F2-4E9D-4624-93D0-B57EDFAC0191@ericabrahamsen.net> <1c2a2c590808110354k1a879a6dm4777d446ea972994@mail.gmail.com> <5FD78F0A-2FF2-4864-97FA-A3DE771DFFC1@ericabrahamsen.net> <1c2a2c590808120545m325737bdj876a13cbd328735f@mail.gmail.com> Message-ID: <405F32C0-287B-43A6-A8C0-8F21CCBCB945@ericabrahamsen.net> Thanks to you both. I'll read up on sockets, but it seems unlikely that it works the way I thought it might... On Aug 12, 2008, at 8:45 PM, Kent Johnson wrote: > On Tue, Aug 12, 2008 at 7:27 AM, Eric Abrahamsen > <eric at ericabrahamsen.net> wrote: >> >> On Aug 11, 2008, at 6:54 PM, Kent Johnson wrote: >>> I'm not sure if you want to see the traffic coming in from your >>> users, >>> or the traffic from your server to the third-party server. I don't >>> know what kind of interaction you want, either. >> >> I'd like to be able to see the response coming back from the third- >> party >> server, and have lighttpd check its headers and either intercept it >> or allow >> it back into the framework. Say if it's got a text content-type >> then let it >> in to the framework, and if it's got an image content-type then >> ignore it or >> throw it away. Rephrasing it this way makes it sound pretty >> unlikely. I >> guess what I wanted was a better sense of how urllib2 uses a socket >> to make >> the request, and how the response, on its way back to my server, >> finds that >> socket. I thought that if the socket file was something that hung >> around >> between requests, I might be able to configure lighttpd to 'listen >> in' on >> that socket, and grab the response if it met certain criteria. But >> if that >> were possible then urllib2 would raise an error, right? > > lighttpd will not see the traffic to the third-party server; the tp > server is not making a request of lighttpd; your code is making a > request of it. The response comes back on the same socket that was > opened by the request; if you want to know how they match up you will > have to learn about TCP/IP which is the underlying network protocol. > This might help: > http://www.amk.ca/python/howto/sockets/ > > If you want to filter the response according to the headers, you can > do that in your code. The response object returned by urllib2 includes > an info() method that gives access to the response headers. > > Kent > > PS Please Reply All to reply to the list. From alan.gauld at btinternet.com Wed Aug 13 20:48:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Aug 2008 19:48:09 +0100 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com><515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com><g7t8sb$5d7$1@ger.gmane.org><20080813041728.2E8DC1E4003@bag.python.org><333efb450808130422y3a625aa0t9ac63f1808b0a711@mail.gmail.com><20080813123116.ADE181E4004@bag.python.org><333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.com> <333efb450808130704v3b71a921ud320071ca7088cc4@mail.gmail.co m> <20080813144253.B55111E4021@bag.python.org> Message-ID: <g7va97$5pg$1@ger.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > (both were included). Can you help me out? gvim is GUI-vim, > I think. Isn't that what I want to learn? Is gvim a cut-down > version of vim, but enables you to use your mouse ( :set mouse=a)? No gvim is a superset of vim. It has more colours, mouse commands, toolbars etc. Plus you can resize windows, scroll, change split window ratios etc But the keyboard command set is identical since the underlying core code is the same. Alan G From tim at johnsons-web.com Thu Aug 14 03:07:12 2008 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 13 Aug 2008 17:07:12 -0800 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <200808131707.12360.tim@johnsons-web.com> On Tuesday 12 August 2008, Jaggo wrote: > Hello. > > I haven't much experience with programming. > > I'd like to point this question to programmers who write in editors other > than the default PyWin32: > > Why do you use your editor rather than using Pywin? What feature has editor > X got that PyWin hasn't? I use emacs. Oh, I work on the linux OS - no Pywin here! :-) Because I am also a lisp programmer, I can write code in elisp to leverage emacs to be more productive. One thing I haven't looked into but am meaning to is a system call pymacs, (quoting the synopsis) """ Pymacs is a powerful tool which, once started from Emacs, allows both-way communication between Emacs Lisp and Python. Pymacs aims Python as an extension language for Emacs rather than the other way around, and this asymmetry is reflected in some design choices. Within Emacs Lisp code, one may load and use Python modules. Python functions may themselves use Emacs services, and handle Emacs Lisp objects kept in Emacs Lisp space. """ MTCW From bgailer at gmail.com Thu Aug 14 03:57:16 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 13 Aug 2008 21:57:16 -0400 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> Message-ID: <48A390FC.2030401@gmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/785cfd9c/attachment.htm> From xboxmuncher at gmail.com Thu Aug 14 05:06:28 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Wed, 13 Aug 2008 23:06:28 -0400 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <200808130323.28861.cfuller084@thinkingplanet.net> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> <200808130323.28861.cfuller084@thinkingplanet.net> Message-ID: <df531c470808132006m529832e0g9c11a8745c2a6745@mail.gmail.com> I'll check out your links. But in response to some of the things said: I'm a fan of indentation, a replacement of indentation with curly braces is not what I was aiming for. If I could have it my way, I'd have indentation and curly braces. I don't want to change official python syntax either.. I just want to be able to easily do it myself. The big problem I had that I didn't explain well enough when I said "visually" is that it is visually hard to tell when code blocks end when other code blocks and statements begin immediately after them. With curly braces you can easily visualize when looking at a lot of code where the code block ends. The best thing you can do in python currently is to put an empty line in between the last line of a code block and the following code, so you can better visualize the end of the code block. On Wed, Aug 13, 2008 at 4:23 AM, Chris Fuller <cfuller084 at thinkingplanet.net > wrote: > > Some clarifications w.r.t. indentation and Python: > http://www.secnetix.de/olli/Python/block_indentation.hawk > > It's just a joke, really: > http://timhatch.com/projects/pybraces/ > > Turnabout is fair play! > http://blog.micropledge.com/2007/09/nobraces/ > > Also, pindent.py in the Tools/scripts directory of your Python distribution > will produce correctly indented scripts if the blocks are designated with > a "#end" line. > > > But seriously, you don't want to go creating a separate class of source > file. > It'll be harder for you and the other programmers to context switch when > working with code that uses the standard style, will confuse others who > won't > know what to do with your code, adds overhead to the compiling, will break > when somebody tries to run it under the standard environment, could clutter > up your development directories, depending on the implementation, etc. > > Here's a thread from 1999 on the Python mailing list that discusses the > issue: > http://mail.python.org/pipermail/python-list/1999-June/004450.html > > There's another script towards the end that might even do what you want, > but > you might want to read what they have to say first :) > > Cheers > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080813/823c4ead/attachment.htm> From flaxeater at gmail.com Thu Aug 14 05:39:00 2008 From: flaxeater at gmail.com (Chad Crabtree) Date: Wed, 13 Aug 2008 23:39:00 -0400 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <df531c470808132006m529832e0g9c11a8745c2a6745@mail.gmail.com> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> <200808130323.28861.cfuller084@thinkingplanet.net> <df531c470808132006m529832e0g9c11a8745c2a6745@mail.gmail.com> Message-ID: <584940990808132039p5856de7nf8d66749b2c3d656@mail.gmail.com> Oh, I forgot there's another way to add braces if it_is_way_cool: #{ print 'coolness' #} On Wed, Aug 13, 2008 at 11:06 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > I'll check out your links. But in response to some of the things said: > I'm a fan of indentation, a replacement of indentation with curly braces is > not what I was aiming for. If I could have it my way, I'd have indentation > and curly braces. I don't want to change official python syntax either.. I > just want to be able to easily do it myself. > > The big problem I had that I didn't explain well enough when I said > "visually" is that it is visually hard to tell when code blocks end when > other code blocks and statements begin immediately after them. With curly > braces you can easily visualize when looking at a lot of code where the code > block ends. The best thing you can do in python currently is to put an empty > line in between the last line of a code block and the following code, so you > can better visualize the end of the code block. > > On Wed, Aug 13, 2008 at 4:23 AM, Chris Fuller > <cfuller084 at thinkingplanet.net> wrote: >> >> Some clarifications w.r.t. indentation and Python: >> http://www.secnetix.de/olli/Python/block_indentation.hawk >> >> It's just a joke, really: >> http://timhatch.com/projects/pybraces/ >> >> Turnabout is fair play! >> http://blog.micropledge.com/2007/09/nobraces/ >> >> Also, pindent.py in the Tools/scripts directory of your Python >> distribution >> will produce correctly indented scripts if the blocks are designated with >> a "#end" line. >> >> >> But seriously, you don't want to go creating a separate class of source >> file. >> It'll be harder for you and the other programmers to context switch when >> working with code that uses the standard style, will confuse others who >> won't >> know what to do with your code, adds overhead to the compiling, will break >> when somebody tries to run it under the standard environment, could >> clutter >> up your development directories, depending on the implementation, etc. >> >> Here's a thread from 1999 on the Python mailing list that discusses the >> issue: >> http://mail.python.org/pipermail/python-list/1999-June/004450.html >> >> There's another script towards the end that might even do what you want, >> but >> you might want to read what they have to say first :) >> >> Cheers >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bgailer at gmail.com Thu Aug 14 05:58:10 2008 From: bgailer at gmail.com (bob gailer) Date: Wed, 13 Aug 2008 23:58:10 -0400 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> Message-ID: <48A3AD52.7060105@gmail.com> Marc Tompkins wrote: > Good Things about SPE: > - Tabbed editing > - "Output" pane, plus separate terminal pane for quickies > - Click on any line in an error traceback to jump to the offending > line. Any file that isn't already, opens automatically when you click > it. > - Left pane toggles between: > - Code outline; specially formatted comment lines appear as > section headers in outline > - Todo list > - Index > - Notes > - TabNanny compiling checker (finds errors that work OK now, but > might bite you later) > - File browser > - Collapse/expand blocks of code for compact viewing > - Syntax highlighting (of course!) > - Code completion, inline help with function/method parameters > - Excellent integration with WinPdb debugger > - Excellent integration with PyDoc documentation > generation/formatting/printing > - TabNanny > > Not-so-Good Things: > - Integrated subversion would be a nice plus. (Actually, I use > Bazaar anyway.) > - Programs you start from inside the IDE run as children of SPE, so > inherit SPE's environment. Not really a Bad Thing, just something to > be aware of - if you make changes to the environment, and want your > program to see them, run it from outside SPE or else restart SPE > (which takes a fraction of the time it takes to restart Eclipse, by > the way.) One thing I really like about Python Win is the integrated debugger, which takes no time to start up. SPE OTOH uses WinPDB which runs as a separate process that takes (in the demo video) 15 seconds to start (each time it is requested)! Since I depend heavily on the debugger that delay would drive me crazy! > -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From xboxmuncher at gmail.com Thu Aug 14 06:08:20 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Thu, 14 Aug 2008 00:08:20 -0400 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <584940990808132039p5856de7nf8d66749b2c3d656@mail.gmail.com> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> <200808130323.28861.cfuller084@thinkingplanet.net> <df531c470808132006m529832e0g9c11a8745c2a6745@mail.gmail.com> <584940990808132039p5856de7nf8d66749b2c3d656@mail.gmail.com> Message-ID: <df531c470808132108n74f28a06u5088bde6378c5e16@mail.gmail.com> I don't see what the big deal is on coming up with the .{ #{, and other bracket types to try to not interfere with normal bracket use in python. Its relatively easy to create a parser to identify the brackets in use normally and the code block brackets, with regex or without. On Wed, Aug 13, 2008 at 11:39 PM, Chad Crabtree <flaxeater at gmail.com> wrote: > Oh, I forgot there's another way to add braces > > if it_is_way_cool: #{ > print 'coolness' > #} > > On Wed, Aug 13, 2008 at 11:06 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > > I'll check out your links. But in response to some of the things said: > > I'm a fan of indentation, a replacement of indentation with curly braces > is > > not what I was aiming for. If I could have it my way, I'd have > indentation > > and curly braces. I don't want to change official python syntax either.. > I > > just want to be able to easily do it myself. > > > > The big problem I had that I didn't explain well enough when I said > > "visually" is that it is visually hard to tell when code blocks end when > > other code blocks and statements begin immediately after them. With curly > > braces you can easily visualize when looking at a lot of code where the > code > > block ends. The best thing you can do in python currently is to put an > empty > > line in between the last line of a code block and the following code, so > you > > can better visualize the end of the code block. > > > > On Wed, Aug 13, 2008 at 4:23 AM, Chris Fuller > > <cfuller084 at thinkingplanet.net> wrote: > >> > >> Some clarifications w.r.t. indentation and Python: > >> http://www.secnetix.de/olli/Python/block_indentation.hawk > >> > >> It's just a joke, really: > >> http://timhatch.com/projects/pybraces/ > >> > >> Turnabout is fair play! > >> http://blog.micropledge.com/2007/09/nobraces/ > >> > >> Also, pindent.py in the Tools/scripts directory of your Python > >> distribution > >> will produce correctly indented scripts if the blocks are designated > with > >> a "#end" line. > >> > >> > >> But seriously, you don't want to go creating a separate class of source > >> file. > >> It'll be harder for you and the other programmers to context switch when > >> working with code that uses the standard style, will confuse others who > >> won't > >> know what to do with your code, adds overhead to the compiling, will > break > >> when somebody tries to run it under the standard environment, could > >> clutter > >> up your development directories, depending on the implementation, etc. > >> > >> Here's a thread from 1999 on the Python mailing list that discusses the > >> issue: > >> http://mail.python.org/pipermail/python-list/1999-June/004450.html > >> > >> There's another script towards the end that might even do what you want, > >> but > >> you might want to read what they have to say first :) > >> > >> Cheers > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/81ada0eb/attachment-0001.htm> From rdm at rcblue.com Thu Aug 14 06:20:50 2008 From: rdm at rcblue.com (Dick Moores) Date: Wed, 13 Aug 2008 21:20:50 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <48A3AD52.7060105@gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> <48A3AD52.7060105@gmail.com> Message-ID: <20080814042103.7E6CF1E4007@bag.python.org> At 08:58 PM 8/13/2008, bob gailer wrote: >One thing I really like about Python Win is the integrated debugger, >which takes no time to start up. SPE OTOH uses WinPDB which runs as >a separate process that takes (in the demo video) 15 seconds to >start (each time it is requested)! Since I depend heavily on the >debugger that delay would drive me crazy! Hm, I just measured how long Ulipad takes to get going with WinPDB, a plug-in: 20 seconds, but 10 seconds for a restart. Other than the time to start, could you compare debugging with Python Win and debugging with WinPDB? Thanks, Dick Moores From timothy.grant at gmail.com Thu Aug 14 07:16:24 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 13 Aug 2008 22:16:24 -0700 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <df531c470808132108n74f28a06u5088bde6378c5e16@mail.gmail.com> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> <200808130323.28861.cfuller084@thinkingplanet.net> <df531c470808132006m529832e0g9c11a8745c2a6745@mail.gmail.com> <584940990808132039p5856de7nf8d66749b2c3d656@mail.gmail.com> <df531c470808132108n74f28a06u5088bde6378c5e16@mail.gmail.com> Message-ID: <e775286d0808132216k2cac191n15ba55acdbaadc3c@mail.gmail.com> On Wed, Aug 13, 2008 at 9:08 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > I don't see what the big deal is on coming up with the .{ #{, and other > bracket types to try to not interfere with normal bracket use in python. Its > relatively easy to create a parser to identify the brackets in use normally > and the code block brackets, with regex or without. > > On Wed, Aug 13, 2008 at 11:39 PM, Chad Crabtree <flaxeater at gmail.com> wrote: >> >> Oh, I forgot there's another way to add braces >> >> if it_is_way_cool: #{ >> print 'coolness' >> #} >> >> On Wed, Aug 13, 2008 at 11:06 PM, xbmuncher <xboxmuncher at gmail.com> wrote: >> > I'll check out your links. But in response to some of the things said: >> > I'm a fan of indentation, a replacement of indentation with curly braces >> > is >> > not what I was aiming for. If I could have it my way, I'd have >> > indentation >> > and curly braces. I don't want to change official python syntax either.. >> > I >> > just want to be able to easily do it myself. >> > >> > The big problem I had that I didn't explain well enough when I said >> > "visually" is that it is visually hard to tell when code blocks end when >> > other code blocks and statements begin immediately after them. With >> > curly >> > braces you can easily visualize when looking at a lot of code where the >> > code >> > block ends. The best thing you can do in python currently is to put an >> > empty >> > line in between the last line of a code block and the following code, so >> > you >> > can better visualize the end of the code block. >> > >> > On Wed, Aug 13, 2008 at 4:23 AM, Chris Fuller >> > <cfuller084 at thinkingplanet.net> wrote: >> >> >> >> Some clarifications w.r.t. indentation and Python: >> >> http://www.secnetix.de/olli/Python/block_indentation.hawk >> >> >> >> It's just a joke, really: >> >> http://timhatch.com/projects/pybraces/ >> >> >> >> Turnabout is fair play! >> >> http://blog.micropledge.com/2007/09/nobraces/ >> >> >> >> Also, pindent.py in the Tools/scripts directory of your Python >> >> distribution >> >> will produce correctly indented scripts if the blocks are designated >> >> with >> >> a "#end" line. >> >> >> >> >> >> But seriously, you don't want to go creating a separate class of source >> >> file. >> >> It'll be harder for you and the other programmers to context switch >> >> when >> >> working with code that uses the standard style, will confuse others who >> >> won't >> >> know what to do with your code, adds overhead to the compiling, will >> >> break >> >> when somebody tries to run it under the standard environment, could >> >> clutter >> >> up your development directories, depending on the implementation, etc. >> >> >> >> Here's a thread from 1999 on the Python mailing list that discusses the >> >> issue: >> >> http://mail.python.org/pipermail/python-list/1999-June/004450.html >> >> >> >> There's another script towards the end that might even do what you >> >> want, >> >> but >> >> you might want to read what they have to say first :) >> >> >> >> Cheers >> >> _______________________________________________ >> >> Tutor maillist - Tutor at python.org >> >> http://mail.python.org/mailman/listinfo/tutor If it's no big deal to parse the braces, I would encourage you to write your own python preprocessor to handle that for you. -- Stand Fast, tjg. [Timothy Grant] From bart.cramer at gmail.com Thu Aug 14 12:05:50 2008 From: bart.cramer at gmail.com (Bart Cramer) Date: Thu, 14 Aug 2008 12:05:50 +0200 Subject: [Tutor] __init__, default values and dict's Message-ID: <2f75e6460808140305g59fa599do4bdc0a5834af8b75@mail.gmail.com> Dear tutors, I have the following code snippet: class N (object) : def __init__ (self, d={}) : self.d = d n1 = N () n1.d['a'] = 1 n2 = N () n2.d['a'] = 2 print n1.d['a'] print n2.d['a'] I assumed that on each call of the __init__ without a dictionary provided, a new dictionary is created. This turns out to be not the case: user at ubuntu804desktop:~$ python test.py 2 2 Does anybody know why this is the case? And what would be the most convenient solution to enforce the dynamic creation of the dictionary? Many thanks for your time and patience, Bart. From Jaggojaggo+Py at gmail.com Thu Aug 14 12:29:17 2008 From: Jaggojaggo+Py at gmail.com (OmerT) Date: Thu, 14 Aug 2008 13:29:17 +0300 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080814042103.7E6CF1E4007@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> <48A3AD52.7060105@gmail.com> <20080814042103.7E6CF1E4007@bag.python.org> Message-ID: <515008f10808140329g54e5503cxa8133e5c3891336a@mail.gmail.com> On Thu, Aug 14, 2008 at 7:20 AM, Dick Moores <rdm at rcblue.com> wrote: > At 08:58 PM 8/13/2008, bob gailer wrote: >> >> One thing I really like about Python Win is the integrated debugger, which >> takes no time to start up. SPE OTOH uses WinPDB which runs as a separate >> process that takes (in the demo video) 15 seconds to start (each time it is >> requested)! Since I depend heavily on the debugger that delay would drive me >> crazy! > > Hm, I just measured how long Ulipad takes to get going with WinPDB, a > plug-in: 20 seconds, but 10 seconds for a restart. > > Other than the time to start, could you compare debugging with Python Win > and debugging with WinPDB? > > Thanks, > > Dick Moores > Isn't that a bit system-dependent? PyWin starts for me in <5 seconds on my spankin' new 2 gb ram, E8400 at 3 ghz. SPE (the .pyw file) took ~7 seconds to start. (Haven't WinPDB to test..) Omer. From benjamin.serrato at gmail.com Thu Aug 14 07:16:55 2008 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Thu, 14 Aug 2008 00:16:55 -0500 Subject: [Tutor] Firefox Bookmarks Message-ID: <dde7cc5d0808132216g7520a649r41bf1245f73670a7@mail.gmail.com> I was trying to learn python a few months back but was distracted. I was up to OO programming. I don't like the way bookmarks work in Firefox so, I would like to take the bookmark file in Firefox 3 and build a markup file from it that shows all of the bookmarked files under their headers with the bookmark comments underneath. The bookmark tags that are supported in FF3 would also be displayed. The next step would be to make the page and thus the places.sqlite file editable to reorder bookmarks under specific headers and edit tags at will. This should allow different attainable, and useful, stages of completion. Are there any modules I should know about? Specifically How can I read/write from places.sqlite? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/c54d1dd0/attachment.htm> From kent37 at tds.net Thu Aug 14 12:37:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Aug 2008 06:37:21 -0400 Subject: [Tutor] __init__, default values and dict's In-Reply-To: <2f75e6460808140305g59fa599do4bdc0a5834af8b75@mail.gmail.com> References: <2f75e6460808140305g59fa599do4bdc0a5834af8b75@mail.gmail.com> Message-ID: <1c2a2c590808140337h5ded6eacl35cdc7eb295eb013@mail.gmail.com> On Thu, Aug 14, 2008 at 6:05 AM, Bart Cramer <bart.cramer at gmail.com> wrote: > Dear tutors, > > I have the following code snippet: > > class N (object) : > > def __init__ (self, d={}) : > self.d = d > > I assumed that on each call of the __init__ without a dictionary > provided, a new dictionary is created. http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Kent From jeff at dcsoftware.com Thu Aug 14 15:36:09 2008 From: jeff at dcsoftware.com (Jeff Johnson) Date: Thu, 14 Aug 2008 06:36:09 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <48A434C9.6080304@dcsoftware.com> I use Dabo's Editor.py. It has templates to provide code highlighting, etc. in many languages. I also like the way it runs Python programs. By the way, Dabo is a database/business object centric framework for Python which wraps WxPython. But you can use just the Editor or other parts you like. It is not intended to be a web framework. http://dabodev.com/wiki/FrontPage -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com Jaggo wrote: > Hello. > > I haven't much experience with programming. > > I'd like to point this question to programmers who write in editors > other than the default PyWin32: > > Why do you use your editor rather than using Pywin? What feature has > editor X got that PyWin hasn't? > (That is, other than "My editor runs on unix / linux"; while that does > count for something it is rather irrelevant to my current situation.) > > Thanks in advance, > Omer. > From zstumgoren at gmail.com Thu Aug 14 16:41:35 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 14 Aug 2008 10:41:35 -0400 Subject: [Tutor] study advice on javascript to python hand-off Message-ID: <cadf44510808140741x3cc344a7i7baae36a15548371@mail.gmail.com> Hi everyone, I've been trying to tackle a certain data-entry and processing problem for quite some time, and I was wondering if someone could offer advice on the path I should take. Whatever the answer, I know I have a great deal of study ahead of me, but I was hoping to at least narrow the field. My specific use-case involves an attempt to create a web-based phone contacts system that allows users to associate a single contact with one or more business entities (or phone numbers or relatives, etc.). On the backend database, I know this requires the use of a linking table and a many-to-many relationship between tables for "individuals" and "businesses." The front end is where I'm running aground. Ideally, I'd like to have a data entry/edit form that lets the client-side user associate multiple entities with a contact before submitting the form to the server. So if the user enters "John Smith" as a contact, they can initially associate him with "ABC Company". If John Smith also serves on the board of directors for XYZ Foundation, I'd like to let the user click an Add button to also associate John Smith with the foundation. All of this should take place before the form is submitted back to the server. A simple javascript implementation of the add/remove functionality I'm speaking of can be found at http://www.dustindiaz.com/add-remove-elements-reprise. The part I'm getting lost on is how to take those dynamic user-generated values and get at them on the server side using python, with the end-goal of parsing and adding the values to the appropriate database tables (I expect I'll also have to do plenty of validation and checking for possible duplicates, but I'm waving my hand at those issues for the moment). So I was hoping someone could explain how to accomplish this seeming hand-off from client-side javascript to server-side python. Should I be accessing the DOM? And if so, should I be parsing URLs or using xml (e.g. python's xml.dom API or Frederick Lundh's ElementTree module)? I suspect that I may be misusing/confusing the terminology here, so please feel free to point out any mistakes. Or perhaps I'm over-complicating the issue and there's a simpler solution to what I'm trying to accomplish. If someone could suggest a conceptual approach to the problem, and even point to some good readings that tie these elements together for the stated purpose, I'd be greatly indebted. Regards, Serdar T. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/91f147e9/attachment.htm> From jeff at dcsoftware.com Thu Aug 14 17:07:38 2008 From: jeff at dcsoftware.com (Jeff Johnson) Date: Thu, 14 Aug 2008 08:07:38 -0700 Subject: [Tutor] study advice on javascript to python hand-off In-Reply-To: <cadf44510808140741x3cc344a7i7baae36a15548371@mail.gmail.com> References: <cadf44510808140741x3cc344a7i7baae36a15548371@mail.gmail.com> Message-ID: <48A44A3A.6000404@dcsoftware.com> This is a three tier framework where you can use any back end you want. They currently support the major ones: MySQL, SQLite, PostGreSQL, MSSql to name the ones I can think of. http://dabodev.com/wiki/FrontPage -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com Serdar Tumgoren wrote: > Hi everyone, > > I've been trying to tackle a certain data-entry and processing problem > for quite some time, and I was wondering if someone could offer advice > on the path I should take. Whatever the answer, I know I have a great > deal of study ahead of me, but I was hoping to at least narrow the field. > > My specific use-case involves an attempt to create a web-based phone > contacts system that allows users to associate a single contact with one > or more business entities (or phone numbers or relatives, etc.). On the > backend database, I know this requires the use of a linking table and a > many-to-many relationship between tables for "individuals" and "businesses." > > The front end is where I'm running aground. > > Ideally, I'd like to have a data entry/edit form that lets the > client-side user associate multiple entities with a contact before > submitting the form to the server. > > So if the user enters "John Smith" as a contact, they can initially > associate him with "ABC Company". > If John Smith also serves on the board of directors for XYZ Foundation, > I'd like to let the user click an Add button to also associate John > Smith with the foundation. All of this should take place before the form > is submitted back to the server. > > A simple javascript implementation of the add/remove functionality I'm > speaking of can be found at > http://www.dustindiaz.com/add-remove-elements-reprise. > > The part I'm getting lost on is how to take those dynamic user-generated > values and get at them on the server side using python, with the > end-goal of parsing and adding the values to the appropriate database > tables (I expect I'll also have to do plenty of validation and checking > for possible duplicates, but I'm waving my hand at those issues for the > moment). > > So I was hoping someone could explain how to accomplish this seeming > hand-off from client-side javascript to server-side python. > > Should I be accessing the DOM? And if so, should I be parsing URLs or > using xml (e.g. python's xml.dom API or Frederick Lundh's ElementTree > module)? > > I suspect that I may be misusing/confusing the terminology here, so > please feel free to point out any mistakes. Or perhaps I'm > over-complicating the issue and there's a simpler solution to what I'm > trying to accomplish. > > If someone could suggest a conceptual approach to the problem, and even > point to some good readings that tie these elements together for the > stated purpose, I'd be greatly indebted. > > Regards, > > Serdar T. > From Mike.Hansen at atmel.com Thu Aug 14 17:27:09 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Thu, 14 Aug 2008 09:27:09 -0600 Subject: [Tutor] study advice on javascript to python hand-off In-Reply-To: <48A44A3A.6000404@dcsoftware.com> References: <cadf44510808140741x3cc344a7i7baae36a15548371@mail.gmail.com> <48A44A3A.6000404@dcsoftware.com> Message-ID: <7941B2693F32294AAF16C26B679A258D033E8648@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Jeff Johnson > Sent: Thursday, August 14, 2008 9:08 AM > To: Serdar Tumgoren > Cc: tutor at python.org > Subject: Re: [Tutor] study advice on javascript to python hand-off > > This is a three tier framework where you can use any back end > you want. > They currently support the major ones: MySQL, SQLite, PostGreSQL, > MSSql to name the ones I can think of. > > http://dabodev.com/wiki/FrontPage > > -- > Jeff > > Jeff Johnson > jeff at dcsoftware.com > Phoenix Python User Group - sunpiggies at googlegroups.com > Dabo might be a good solution if you are making GUI client-side apps. Note that the OP mentioned using Javascript, so I'm assuming that the OP is thinking about a web-based front end. It really depends on the number of users and other factors. If there are many users, then a web-based front end is possibly better in that each user does not have to install software to use the application.(Only the browser is required) Having each user install software can become a maintenance nightmare if not implemented properly. Having the entire application on a server allows you to make changes without having to deploy it to many users. On client-side GUI apps, it'd be good to develop something that checks if a new version of the software is necessary to download. Oh well, I think I've babbled on enough about client side apps vs web-based server side apps. I guess you get the idea. Mike From zstumgoren at gmail.com Thu Aug 14 17:34:39 2008 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 14 Aug 2008 11:34:39 -0400 Subject: [Tutor] study advice on javascript to python hand-off In-Reply-To: <7941B2693F32294AAF16C26B679A258D033E8648@csomb01.corp.atmel.com> References: <cadf44510808140741x3cc344a7i7baae36a15548371@mail.gmail.com> <48A44A3A.6000404@dcsoftware.com> <7941B2693F32294AAF16C26B679A258D033E8648@csomb01.corp.atmel.com> Message-ID: <cadf44510808140834r217ec5d0ved198d1948851403@mail.gmail.com> Thanks all for the quick responses. Yes, though Dabo looks like an interesting tool, I am headed the route of a web-based form. @Chad: I haven't checked out Turbogears but have been dabbling with django for a bit. Djanog's baked-in admin interface for data entry approaches what I'm trying to accomplish, but doesn't quite get me there. But I figured I needed to get back to basics. So just to clarify, is this indeed something that is properly accomplished using Ajax? (whether xml or json)? Meantime, I'll get started reading up on HTTP. It's one area I haven't really delved into yet. Thanks again! On Thu, Aug 14, 2008 at 11:27 AM, Hansen, Mike <Mike.Hansen at atmel.com>wrote: > > -----Original Message----- > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On Behalf Of Jeff Johnson > > Sent: Thursday, August 14, 2008 9:08 AM > > To: Serdar Tumgoren > > Cc: tutor at python.org > > Subject: Re: [Tutor] study advice on javascript to python hand-off > > > > This is a three tier framework where you can use any back end > > you want. > > They currently support the major ones: MySQL, SQLite, PostGreSQL, > > MSSql to name the ones I can think of. > > > > http://dabodev.com/wiki/FrontPage > > > > -- > > Jeff > > > > Jeff Johnson > > jeff at dcsoftware.com > > Phoenix Python User Group - sunpiggies at googlegroups.com > > > > Dabo might be a good solution if you are making GUI client-side apps. > Note that the OP mentioned using Javascript, so I'm assuming that the > OP is thinking about a web-based front end. It really depends on the > number of users and other factors. If there are many users, then a > web-based front end is possibly better in that each user does not have > to install software to use the application.(Only the browser is > required) Having each user install software can become a maintenance > nightmare if not implemented properly. Having the entire application > on a server allows you to make changes without having to deploy it to > many users. On client-side GUI apps, it'd be good to develop something > that checks if a new version of the software is necessary to download. > > Oh well, I think I've babbled on enough about client side apps vs > web-based server side apps. I guess you get the idea. > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Serdar Tumgoren The Record 150 River Street Hackensack, NJ 07601 201-403-0834 tumgoren at northjersey.com northjersey.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/5f533c89/attachment.htm> From Mike.Hansen at atmel.com Thu Aug 14 18:07:16 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Thu, 14 Aug 2008 10:07:16 -0600 Subject: [Tutor] study advice on javascript to python hand-off In-Reply-To: <cadf44510808140834r217ec5d0ved198d1948851403@mail.gmail.com> References: <cadf44510808140741x3cc344a7i7baae36a15548371@mail.gmail.com><48A44A3A.6000404@dcsoftware.com><7941B2693F32294AAF16C26B679A258D033E8648@csomb01.corp.atmel.com> <cadf44510808140834r217ec5d0ved198d1948851403@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D03458136@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Serdar Tumgoren > Sent: Thursday, August 14, 2008 9:35 AM > To: tutor at python.org > Subject: Re: [Tutor] study advice on javascript to python hand-off > > Thanks all for the quick responses. > > Yes, though Dabo looks like an interesting tool, I am headed > the route of a web-based form. > > @Chad: I haven't checked out Turbogears but have been > dabbling with django for a bit. > > Djanog's baked-in admin interface for data entry approaches > what I'm trying to accomplish, but doesn't quite get me there. > > But I figured I needed to get back to basics. So just to > clarify, is this indeed something that is properly > accomplished using Ajax? (whether xml or json)? > > Meantime, I'll get started reading up on HTTP. It's one area > I haven't really delved into yet. > > Thanks again! You might look at using a JavaScript toolkit like Dojo to handle your AJAX and JavaScript events. The nice thing about these is they make it easy to do AJAX calls and work across multiple browsers. JQuery seems to be the popular one now, but there are many JavaScript toolkits to choose from. Mike From alan.gauld at btinternet.com Thu Aug 14 19:32:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Aug 2008 18:32:15 +0100 Subject: [Tutor] __init__, default values and dict's References: <2f75e6460808140305g59fa599do4bdc0a5834af8b75@mail.gmail.com> Message-ID: <g81q6u$sst$1@ger.gmane.org> "Bart Cramer" <bart.cramer at gmail.com> wrote > Does anybody know why this is the case? And what would be the most > convenient solution to enforce the dynamic creation of the > dictionary? Kent answered the first bit. For the second try def __init__(self, d=None): if not d: d = {} self.d = d HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Aug 14 19:46:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Aug 2008 13:46:22 -0400 Subject: [Tutor] __init__, default values and dict's In-Reply-To: <g81q6u$sst$1@ger.gmane.org> References: <2f75e6460808140305g59fa599do4bdc0a5834af8b75@mail.gmail.com> <g81q6u$sst$1@ger.gmane.org> Message-ID: <1c2a2c590808141046u3327dbdfj915bb61db9861ce7@mail.gmail.com> On Thu, Aug 14, 2008 at 1:32 PM, Alan Gauld <alan.gauld at btinternet.com> wrote: > For the second try > > def __init__(self, d=None): > if not d: I would use if d is None: so the user can explicitly pass e.g. an empty dict. Kent From alan.gauld at btinternet.com Thu Aug 14 22:37:47 2008 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 14 Aug 2008 20:37:47 +0000 (GMT) Subject: [Tutor] __init__, default values and dict's Message-ID: <662771.10449.qm@web86708.mail.ukl.yahoo.com> > def __init__(self, d=None): > if not d: > > I would use > if d is None: > so the user can explicitly pass e.g. an empty dict. Good catch. I agree. Alan G. From joeturf at gmail.com Fri Aug 15 01:08:30 2008 From: joeturf at gmail.com (Joseph Bae) Date: Thu, 14 Aug 2008 16:08:30 -0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined Message-ID: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> Hi all, I'm new to Python (and programming in general) and need some help! Here is my code so far for a temperature conversion program (converts between Fahrenheit and Celsius): temp = input("Enter A Number : ") convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") if convertTo == "F": convertedTemp = convertToFahrenheit(temp) print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) else: convertedTemp = convertToCelsius(temp) print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) def convertToFahrenheit(t): tF = (9.0/5.0) * (t + 32) return tF def convertToCelsius(t): tC = (9.0/5.0) * (t - 32) return tC It worked fine without having extra functions but once I put convertToFahrenheit and convertToCelsius in (just for practice really), this happened: Enter A Number : 50 Convert to (F)ahrenheit or (C)elsius? : F Traceback (most recent call last): File "TemperatureConverter.py", line 5, in <module> convertedTemp = convertToFahrenheit(temp) NameError: name 'convertToFahrenheit' is not defined This is most likely a very simple error, but can someone please clarify for me why it's behaving this way? Thanks! Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/6d0ddb34/attachment-0001.htm> From hugonz-lists at h-lab.net Fri Aug 15 01:21:45 2008 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 14 Aug 2008 18:21:45 -0500 Subject: [Tutor] Firefox Bookmarks In-Reply-To: <dde7cc5d0808132216g7520a649r41bf1245f73670a7@mail.gmail.com> References: <dde7cc5d0808132216g7520a649r41bf1245f73670a7@mail.gmail.com> Message-ID: <48A4BE09.5010500@h-lab.net> > Are there any modules I should know about? Specifically How can I > read/write from places.sqlite? Hi, pysqlite3 is the python wrapper for the SQLite libs. It is included with Python 2.5 and newer. Docs are at http://oss.itsystementwicklung.de/download/pysqlite/doc/usage-guide.html Have fun Hugo From rosenville at gmail.com Fri Aug 15 01:26:18 2008 From: rosenville at gmail.com (Josh Rosen) Date: Thu, 14 Aug 2008 16:26:18 -0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> Message-ID: <6C1F1AD1-15E7-42CD-B3C0-291BA351C67B@gmail.com> In Python, def is an executable statement. Your function is not defined until the def statement is run by Python. If you move your function definitions earlier in the code so that your functions are defined before they're used, this code will run properly. Josh R. On Aug 14, 2008, at 4:08 PM, Joseph Bae wrote: > Hi all, > > I'm new to Python (and programming in general) and need some help! > > Here is my code so far for a temperature conversion program > (converts between Fahrenheit and Celsius): > > > > temp = input("Enter A Number : ") > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") > > if convertTo == "F": > convertedTemp = convertToFahrenheit(temp) > print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) > else: > convertedTemp = convertToCelsius(temp) > print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) > > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > return tF > > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > return tC > > > > It worked fine without having extra functions but once I put > convertToFahrenheit and convertToCelsius in (just for practice > really), this happened: > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? : F > Traceback (most recent call last): > File "TemperatureConverter.py", line 5, in <module> > convertedTemp = convertToFahrenheit(temp) > NameError: name 'convertToFahrenheit' is not defined > > This is most likely a very simple error, but can someone please > clarify for me why it's behaving this way? > > Thanks! > > Joe > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/4091df66/attachment.htm> From emadnawfal at gmail.com Fri Aug 15 01:29:57 2008 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Thu, 14 Aug 2008 19:29:57 -0400 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> Message-ID: <652641e90808141629g349dae2cya3c1738ba7542301@mail.gmail.com> On Thu, Aug 14, 2008 at 7:08 PM, Joseph Bae <joeturf at gmail.com> wrote: > Hi all, > > I'm new to Python (and programming in general) and need some help! > > Here is my code so far for a temperature conversion program (converts > between Fahrenheit and Celsius): > > > > temp = input("Enter A Number : ") > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") > > if convertTo == "F": > convertedTemp = convertToFahrenheit(temp) > print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) > else: > convertedTemp = convertToCelsius(temp) > print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) > > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > return tF > > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > return tC > > > > It worked fine without having extra functions but once I put > convertToFahrenheit and convertToCelsius in (just for practice really), this > happened: > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? : F > Traceback (most recent call last): > File "TemperatureConverter.py", line 5, in <module> > convertedTemp = convertToFahrenheit(temp) > NameError: name 'convertToFahrenheit' is not defined > > This is most likely a very simple error, but can someone please clarify for > me why it's behaving this way? > You just need to define the functions before you use them Arranging the order od your program makes it work. Like this def convertToFahrenheit(t): tF = (9.0/5.0) * (t + 32) return tF def convertToCelsius(t): tC = (9.0/5.0) * (t - 32) return tC temp = input("Enter A Number : ") convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") if convertTo == "F": convertedTemp = convertToFahrenheit(temp) print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) else: convertedTemp = convertToCelsius(temp) print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) > > > Thanks! > > Joe > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080814/2b92a780/attachment.htm> From vivien.moreau at neuf.fr Fri Aug 15 01:30:54 2008 From: vivien.moreau at neuf.fr (Tuxicomane) Date: Fri, 15 Aug 2008 01:30:54 +0200 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> (Joseph Bae's message of "Thu\, 14 Aug 2008 16\:08\:30 -0700") References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> Message-ID: <877iajqimp.fsf@esteban.serengeti.homelinux.net> Joseph Bae <joeturf at gmail.com> writes: > Hi all, Hi ! (and sorry for my approximative English ... ;-) > I'm new to Python (and programming in general) and need some help! > > Here is my code so far for a temperature conversion program >(converts between Fahrenheit and Celsius): > > temp = input("Enter A Number : ") > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") > > if convertTo == "F": > convertedTemp = convertToFahrenheit(temp) > print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) > else: > convertedTemp = convertToCelsius(temp) > print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) > > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > return tF > > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > return tC > > It worked fine without having extra functions but once I put > convertToFahrenheit and convertToCelsius in (just for practice > really), this happened: > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? : F > Traceback (most recent call last): > File "TemperatureConverter.py", line 5, in <module> > convertedTemp = convertToFahrenheit(temp) > NameError: name 'convertToFahrenheit' is not defined > > This is most likely a very simple error, but can someone please > clarify for me why it's behaving this way? Well, you have to define the function convertToFahrenheit *before* you use it ! Then it should work as you want ;-) > Thanks! > > Joe You're welcome (and apologizes for my bad and simple English :-) -- Vivien Moreau. From john at fouhy.net Fri Aug 15 01:40:55 2008 From: john at fouhy.net (John Fouhy) Date: Fri, 15 Aug 2008 11:40:55 +1200 Subject: [Tutor] Firefox Bookmarks In-Reply-To: <dde7cc5d0808132216g7520a649r41bf1245f73670a7@mail.gmail.com> References: <dde7cc5d0808132216g7520a649r41bf1245f73670a7@mail.gmail.com> Message-ID: <5e58f2e40808141640o468ee9d9sc6fb2f215e63519f@mail.gmail.com> 2008/8/14 Benjamin Serrato <benjamin.serrato at gmail.com>: > Are there any modules I should know about? Specifically How can I read/write > from places.sqlite? Here's some code to get you stared (requires python 2.5): >>> import sqlite3 >>> db = sqlite3.connect('places.sqlite') >>> c = db.cursor() >>> c.execute('select * from sqlite_master') >>> table_info = c.fetchall() ### by inspecting table_info, you can get some idea of the structure of the Firefox database (assuming you don't know the structure anyway). For instance, here's a list of the table names: >>> [x[1] for x in table_info if x[0] == 'table'] [u'moz_bookmarks', u'moz_bookmarks_roots', u'moz_keywords', u'sqlite_sequence', u'moz_favicons', u'moz_annos', u'moz_anno_attributes', u'moz_items_annos', u'moz_places', u'moz_historyvisits', u'moz_inputhistory'] I'm assuming here that you know SQL. If you don't, this may be hard :-) Here is a general tip for writing SQL in code: This is BAD: c.execute('select * from my_table where my_var = %s' % search_string) This is GOOD: c.execute('select * from my_table where my_var = ?', (search_string,)) Finally, it appears you may have trouble writing to places.sqlite while firefox is running. Heck, I couldn't even read from it -- had to take a copy of the database and inspect this. It seems that firefox keeps a transaction open which has the effect of locking the whole database (SQLite supports concurrent access, but it can only lock the entire database). I guess that's fair enough -- from Firefox's point of view, they don't really want people messing with the database while they're using it -- but it may make your plans more difficult. -- John. From bgailer at gmail.com Fri Aug 15 01:54:21 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 14 Aug 2008 19:54:21 -0400 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080814042103.7E6CF1E4007@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> <48A3AD52.7060105@gmail.com> <20080814042103.7E6CF1E4007@bag.python.org> Message-ID: <48A4C5AD.2030808@gmail.com> Dick Moores wrote: > At 08:58 PM 8/13/2008, bob gailer wrote: >> One thing I really like about Python Win is the integrated debugger, >> which takes no time to start up. SPE OTOH uses WinPDB which runs as a >> separate process that takes (in the demo video) 15 seconds to start >> (each time it is requested)! Since I depend heavily on the debugger >> that delay would drive me crazy! > > Hm, I just measured how long Ulipad takes to get going with WinPDB, a > plug-in: 20 seconds, but 10 seconds for a restart. Since you mention Ulipad I may have tried WinPDB there instead of SPE. I just remember trying it and not liking it. Python Win is totally integrated and seamless. > > Other than the time to start, could you compare debugging with Python > Win and debugging with WinPDB? I'll taks a stab. All I know about WinPDB is what I see in the SPE video, so it probably is not the truth. What I see is a screen cluttered with a lot of windows, and having to switch application to access the output window or the code editor to make changes. Wth PyWin I work in the same familiar environment. The interactive window is available for viewing output and entering Python statements and expressions. If I want to see the stack or watch variables I can open floating or dockable windows. Python Win serves my workflow. I am editing a script. I decide to run it so I can see what steps it takes and what values my variables are getting. All I have to is press F10 in the active window and execution starts with the first statement. I can set breakpoints with F9, control execution with F11 F10 shift-F11 F5 and shift-F5. I can edit my source on the fly (changes of course do not take effect until the next execution cycle, and I must take care to not delete or add lines (the debugger does not know about such changes). I can set a condition for a breakpoint. OTOH WinPDB displays more information (witness locals globals exceptions and threads). I don't know how PythonWin handles threads. YMMV. HTH. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From rdm at rcblue.com Fri Aug 15 02:23:05 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 14 Aug 2008 17:23:05 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <48A4C5AD.2030808@gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <g7t8sb$5d7$1@ger.gmane.org> <20080813041728.2E8DC1E4003@bag.python.org> <g7u374$v46$1@ger.gmane.org> <5487b3060808130110o7ac3778bt679dc2de20681d9e@mail.gmail.com> <40af687b0808130306w2c9740a2n4b44539b65e52d38@mail.gmail.com> <48A3AD52.7060105@gmail.com> <20080814042103.7E6CF1E4007@bag.python.org> <48A4C5AD.2030808@gmail.com> Message-ID: <20080815002318.3273B1E4007@bag.python.org> At 04:54 PM 8/14/2008, bob gailer wrote: >Dick Moores wrote: >>At 08:58 PM 8/13/2008, bob gailer wrote: >>>One thing I really like about Python Win is the integrated >>>debugger, which takes no time to start up. SPE OTOH uses WinPDB >>>which runs as a separate process that takes (in the demo video) 15 >>>seconds to start (each time it is requested)! Since I depend >>>heavily on the debugger that delay would drive me crazy! >> >>Hm, I just measured how long Ulipad takes to get going with WinPDB, >>a plug-in: 20 seconds, but 10 seconds for a restart. > >Since you mention Ulipad I may have tried WinPDB there instead of >SPE. I just remember trying it and not liking it. Python Win is >totally integrated and seamless. >>Other than the time to start, could you compare debugging with >>Python Win and debugging with WinPDB? > >I'll taks a stab. All I know about WinPDB is what I see in the SPE >video, so it probably is not the truth. What I see is a screen >cluttered with a lot of windows, and having to switch application to >access the output window or the code editor to make changes. Wth >PyWin I work in the same familiar environment. The interactive >window is available for viewing output and entering Python >statements and expressions. If I want to see the stack or watch >variables I can open floating or dockable windows. > >Python Win serves my workflow. I am editing a script. I decide to >run it so I can see what steps it takes and what values my variables >are getting. > >All I have to is press F10 in the active window and execution starts >with the first statement. I can set breakpoints with F9, control >execution with F11 F10 shift-F11 F5 and shift-F5. I can edit my >source on the fly (changes of course do not take effect until the >next execution cycle, and I must take care to not delete or add >lines (the debugger does not know about such changes). > >I can set a condition for a breakpoint. > >OTOH WinPDB displays more information (witness locals globals >exceptions and threads). I don't know how PythonWin handles threads. Thanks very much for taking the time to write about something I've long wondered about. As a Python learner, I found that getting acquainted with WinPDB made such a big difference in my ability to program, that I'm reluctant to change. I learned to use it through <https://gotgenes.com/swcatvtwiki/DebuggingExercise> BTW you can set a condition for a breakpoint with it: See this example towards the bottom of the tutorial: ================================== we need to set our conditional breakpoint. Look for the line number of the while loop statement: while divisor <= 0:and set a conditional breakpoint for when divisor reaches the value 1. bp 35, divisor == 1 ==================================== Dick From rdm at rcblue.com Fri Aug 15 03:58:17 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 14 Aug 2008 18:58:17 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <48A434C9.6080304@dcsoftware.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <48A434C9.6080304@dcsoftware.com> Message-ID: <20080815015830.607D01E4007@bag.python.org> At 06:36 AM 8/14/2008, Jeff Johnson wrote: >I use Dabo's Editor.py. It has templates to provide code >highlighting, etc. in many languages. I also like the way it runs >Python programs. Could you tell us what you like about the way it runs Python programs? Thanks, Dick Moores >By the way, Dabo is a database/business object centric framework for >Python which wraps WxPython. But you can use just the Editor or >other parts you like. It is not intended to be a web framework. > >http://dabodev.com/wiki/FrontPage From alan.gauld at btinternet.com Fri Aug 15 07:50:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Aug 2008 06:50:09 +0100 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> Message-ID: <g835eg$bjn$1@ger.gmane.org> "Joseph Bae" <joeturf at gmail.com> wrote > temp = input("Enter A Number : ") > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") > > if convertTo == "F": > convertedTemp = convertToFahrenheit(temp) > print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) > else: > convertedTemp = convertToCelsius(temp) > print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) > > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > return tF > > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > return tC > > convertedTemp = convertToFahrenheit(temp) > NameError: name 'convertToFahrenheit' is not defined > > This is most likely a very simple error, but can someone please > clarify for > me why it's behaving this way? Others have explained that you need to execute the function definitions before Python sees the name. You can do this in two ways depending on taste. 1) As suggested move your main code below the function definitions. 2) move your main code into a function - traditionally called main() then call main as the last line of your code. The second method has two advantages: 1) It maintains the top-down design style if thats your preferred style 2) It makes it much easier to make the file into a reusable module. It has two minor disadvantages: 1) The extra function call (main() ) slows things down by a tiny amount 2) the extra indentation level of being inside a function reduces the page width slightly HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From shiv_mbm at hotmail.com Fri Aug 15 09:54:43 2008 From: shiv_mbm at hotmail.com (ShivKumar Anand) Date: Fri, 15 Aug 2008 13:24:43 +0530 Subject: [Tutor] Image Matching Message-ID: <BAY121-W348A31872A92A44115DBE7F66D0@phx.gbl> Hello!! Everyone, I have to match two images and tell how much identical they are. I am trying with Python Imaging Library 1.2.6, but not able to do it I am using ImageChops.difference(im1, im2).histogram() and trying to achieve. regards Shiv Kumar _________________________________________________________________ Searching for the best deals on travel? Visit MSN Travel. http://msn.coxandkings.co.in/cnk/cnk.do -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080815/fa6dcfde/attachment.htm> From kent37 at tds.net Fri Aug 15 13:10:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Aug 2008 07:10:19 -0400 Subject: [Tutor] Image Matching In-Reply-To: <BAY121-W348A31872A92A44115DBE7F66D0@phx.gbl> References: <BAY121-W348A31872A92A44115DBE7F66D0@phx.gbl> Message-ID: <1c2a2c590808150410r523442ccnff09efb48a59b2af@mail.gmail.com> On Fri, Aug 15, 2008 at 3:54 AM, ShivKumar Anand <shiv_mbm at hotmail.com> wrote: > Hello!! Everyone, > > I have to match two images and tell how much identical they are. > > I am trying with Python Imaging Library 1.2.6, but not able to do it > > I am using ImageChops.difference(im1, im2).histogram() and trying to > achieve. How do you define "how much identical"? What results are you getting and how does it not work? Kent From lie.1296 at gmail.com Fri Aug 15 13:14:18 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 15 Aug 2008 18:14:18 +0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <mailman.15566.1218639544.920.tutor@python.org> References: <mailman.15566.1218639544.920.tutor@python.org> Message-ID: <1218798858.6352.25.camel@lieryan-laptop> On Wed, 2008-08-13 at 16:59 +0200, tutor-request at python.org wrote: > > Message: 2 > Date: Wed, 13 Aug 2008 09:04:40 -0500 > From: "W W" <srilyk at gmail.com> > Subject: Re: [Tutor] What has Editor X got that PyWin32 hasn't? > To: "Dick Moores" <rdm at rcblue.com> > Cc: Python Tutor List <tutor at python.org> > Message-ID: > <333efb450808130704v3b71a921ud320071ca7088cc4 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > As far as vi/vim being better than other editors, well that depends on > your > personal preference and experience, but if you're a touch typist, > prefer to > use the keyboard, and hate wasting motions and extra keystrokes... > vi/vim > is probably for you. I've seen vi(m) being praised a lot, well, personally the thing that I hate the most about vim is its directional button (khjl) which is unnatural (a better choice would be gamer's wasd or ijkl[1], even jhkl would be better (like the default except with the up and down inverted)). I found most of the hotkeys provided in vi(m) useless, why? Because I'm using a laptop and is very adept at using touchpad, 1) there is only a very short distance for going back and forth between the touchpad and keyboard 2) the keyboard is smaller, 3) many of the hotkeys require pressing Esc first to get out from editing/inserting mode, which is just as inconvenient as reaching the Ctrl. And for vi(m), after going to command/shortcut mode and pressing the shortcut, then most of the time you have to go back to editing mode by pressing i/a/etc, that is much worse than the Ctrl craziness. So, a simple recommendation from me: If you're a programmer (or a fast typer) and you hate vim but hate using the mouse even further, try buying a laptop and get a degree in touchpad mastery [1] if you argued that w or i is not in the home position, neither is h. From jeff at dcsoftware.com Fri Aug 15 17:23:18 2008 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 15 Aug 2008 08:23:18 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <20080815015830.607D01E4007@bag.python.org> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <48A434C9.6080304@dcsoftware.com> <20080815015830.607D01E4007@bag.python.org> Message-ID: <48A59F66.8080004@dcsoftware.com> It has a Run command on the menu and copies your .py to a temp file and executes it. Output is displayed in the lower split window. It works very nice without ever having to leave the editor. I will tell you that I am not a person that likes a lot of features. It does indenting and code coloring and I can make changes, save and run it all in the editor. YMMV -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com Dick Moores wrote: > At 06:36 AM 8/14/2008, Jeff Johnson wrote: >> I use Dabo's Editor.py. It has templates to provide code >> highlighting, etc. in many languages. I also like the way it runs >> Python programs. > > Could you tell us what you like about the way it runs Python programs? > > Thanks, > > Dick Moores > From jeff at dcsoftware.com Fri Aug 15 17:25:55 2008 From: jeff at dcsoftware.com (Jeff Johnson) Date: Fri, 15 Aug 2008 08:25:55 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <0MKofY-1KU19t2SjE-0006Xi@mx.perfora.net> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> <48A434C9.6080304@dcsoftware.com> <20080815015830.607D01E4007@bag.python.org> <48A5953A.1030205@dcsoftware.com> <0MKofY-1KU19t2SjE-0006Xi@mx.perfora.net> Message-ID: <48A5A003.1080000@dcsoftware.com> You can use just the Editor if you wish. Editor.py is the program. Dick Moores wrote: > Thanks for the info. I'll take a look at Dabo. > > Dick > -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From gregor.lingl at aon.at Fri Aug 15 22:28:06 2008 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 15 Aug 2008 22:28:06 +0200 Subject: [Tutor] Questions about the new turtle module in Python 2.6b2 In-Reply-To: <489E913D.60507@aon.at> References: <20080809101310.2AE531E4002@bag.python.org> <489E913D.60507@aon.at> Message-ID: <48A5E6D6.5000102@aon.at> Hi Dick, as I promised some days ago, here is an event driven version of a rectangle generator, which is based on my first example: from turtle import * from random import random, randint from time import sleep MAXLEN = 30 MAXWID = 25 def randomcolor(): return random(), random(), random() def pause(x,y): global running running = not running if running: title("RUNNING... - CLICK TO HALT") else: title("HALTED... - CLICK TO CONTINUE") def squares(x,y): clear() title("RUNNING... - CLICK TO HALT") onscreenclick(pause) for cycle in range(randint(3, 5)): bgcolor(randomcolor()) for rect in range(randint(5,10)): shapesize(3 + random()*MAXLEN, 3 + random()*MAXWID, randint(3, 10)) color(randomcolor(), randomcolor()) stamp() update() sleep(1) update() while not running: # now pausing sleep(0.5) update() sleep(1) clearstamps() bgcolor("white") pencolor("black") write("Click to exit!", align="center", font=("Arial", 24, "bold")) title("") exitonclick() reset() title("Python turtle graphics: random rectangle generator") hideturtle() resizemode("user") shape("square") running = True onscreenclick(squares) listen() write("Click me!", align="center", font=("Arial", 24, "bold")) mainloop() ######## end of program A short explanation: In event driven programs you have to ecapsulate all actions in functions (or methods when using oop-techniques) which have to be bound to some events. In this example this happens via the onscreenclick() function. The functions that perform the desired actions are not called in the main program. Instead the main program calls the mainloop() which is a loop waiting for events. If such an event - like a mouse click - occurs the function bound to this event will be called. This function may rebind the event to another action - as is done in squares - line three. So in this example the first click starts the rectangle generator, subsequent clicks will swith the running-state. (The last click wil terminate the program.) Making a program pause needs a special trick: the pause() function + boolean variable running. update() is used to make the program check the event-queue. (This would not be necessary, I think, if you draw rectangles slowly using goto(), because in this case the animation itself automatically uses update() frequently.) Hope this helps - if not feel free to aks again Gregor Gregor Lingl schrieb: > Dick Moores schrieb: >> Gregor, >> >> <http://docs.python.org/dev/library/turtle.html#turtle.setup> >> 1. I want the window to open with the right edge 0 pixels from the >> right edge of my screen. >> However, setup(width=.75, height=.915, startx=-0, starty=0) doesn't >> work. I have to do the nearest thing, >> setup(width=.75, height=.915, startx=-1, starty=0). A small thing, >> but what's wrong with perfection. >> > Hi Dick, > a good observation, but I think this cannot be changed, because of > > >>> -0 == 0 > True > > in Python >> 2. There's a lot I don't understand in >> turtle.setup(width=_CFG[, "width"], height=_CFG[, "height"], >> startx=_CFG[, "leftright"], starty=_CFG[, "topbottom"]) >> >> What is '_CFG'? And how should anyone know what it is? >> What is "leftright"? And how to use it? >> What is "topbottom"? And how to use it? >> > _CFG is an internal dictionary, which contains configuration data. You > can change these > by editing adding or editing the turtle.cfg file (an example is in the > Demo directory). > How to do this you can find here: > > http://docs.python.org/dev/library/turtle.html#how-to-configure-screen-and-turtles > >> 3. http://docs.python.org/dev/library/turtle.html#turtle.stamp >> >> "turtle.stamp() >> Stamp a copy of the turtle shape onto the canvas at the current >> turtle position. Return a stamp_id for that stamp, which can be used >> to delete it by calling clearstamp(stamp_id)." >> >> But in your version 1 >> (<http://article.gmane.org/gmane.comp.python.tutor/49805>), the >> turtle is hidden by hideturtle()! What are you stamping? It seems the >> shape, or rectangle. If so, why does the doc say 'turtle'? >> > there will be stamped the shape of the turtle, that appeared if it > were not hidden. > > General remark: you can investigate Python and especially its turtle > module interactively > using IDLE. But note: in the case of graphics (Tkinter and especially > turtle.py) you have to > use the -n switch of IDLE. So the link calling idle must look > something like this: > > /... ../... ../python /... ../.../.../idle.pyw -n > > the dotted parts representig the path according to your system > configuration > > If you have done this onceyou can issue function calls on after > another and > observe what happens. E. g.: > > >>> from turtle import * > >>> reset() > >>> shape("square") > >>> color("blue", "red") > >>> resizemode("user") # at first no visual effect, but ... > >>> turtlesize(2,3,5) > >>> fd(100) > >>> left(45) > >>> pensize(8) > >>> fd(100) > >>> left(90) > >>> pencolor("green") > >>> fd(100) > >>> turtlesize(1,5) > >>> left(1080) > >>> stamp() > 8 > >>> left(45) > >>> ht() > >>> fd(100) > >>> stamp() > 9 > >>> left(45) > >>> fd(100) > >>> stamp() > 10 > >>> > > ... and so on. > If you want to know how some function works and the docs > don't give you a proper clue, simply try out. >> 4. For my random_rectangles.py program I've started to try out the >> new turtle. (See the current state of random_rectanglesV16_web.py at >> <http://py77.python.pastebin.com/d3e842821>.) The only downside I've >> found is that the new turtle is much faster that the old. I want to >> set the speed so that the outlines of rectangles are drawn slowly >> enough that the user (me at present) can both appreciate the colors >> and have time to check the names of the colors being printed in the >> console window. Using the old turtle, I found that a default delay of >> 1 ((delay(1)) was just right; with the new turtle, setting a delay of >> even 50 affects only the first cycle of rectangles. So I don't use >> delay at all. Setting the slowest speed of 1 (speed(1)) is still too >> fast. How can I slow down the drawing of the rectangles? >> > I suppose you have some call of reset() or clear() which resets the > delay. So try a > delay call at the beginning of every cycle. >> 5. I've been unable to figure out how to use onclick() >> (<http://docs.python.org/dev/library/turtle.html#turtle.onclick>). >> I'd like to find a way to pause my script by clicking on the screen >> -- so I could snag an image of what's showing, and then click again >> to restart the drawing of the rectangles. And in addition, being able >> to stop the program with a double click on the screen would be very >> handy. Could you explain how to do these, if in fact they are possible? >> > This idea for an event driven program affords a bit of different > thinking and a different > program structure. I'll come up with a proposition and an explanation > of some > prerequisites in another posting. (I have not got the time to do > that now). > > Regards, > Gregor >> That's all for now. >> >> Thanks, >> >> Dick >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > From alan.gauld at btinternet.com Fri Aug 15 22:31:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Aug 2008 21:31:51 +0100 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? References: <mailman.15566.1218639544.920.tutor@python.org> <1218798858.6352.25.camel@lieryan-laptop> Message-ID: <g84p3n$5n8$1@ger.gmane.org> "Lie Ryan" <lie.1296 at gmail.com> wrote > I've seen vi(m) being praised a lot, well, personally the thing that > I > hate the most about vim is its directional button (khjl) which is > unnatural But very logical and easy to remember when you recall that ^H was backspace (go left), and ^j was linefeed (go down) and the typists home position has the right hand on ,j,k,l, (and if you use your imagination K looks a bit like an up arrow and L like a right facing symbol - but personally I think that's coincidental!) and shifting one position left is an easy reach. (BTW A lot of early terminal games, especially on Unix use the hjkl format. And so, of course does the bash shell and more (and maybe less?) ) > touchpad and keyboard 2) the keyboard is smaller, 3) many of the > hotkeys > require pressing Esc first to get out from editing/inserting mode, > which > is just as inconvenient as reaching the Ctrl. And for vi(m), after > going > to command/shortcut mode and pressing the shortcut, then most of the > time you have to go back to editing mode by pressing i/a/etc, that > is > much worse than the Ctrl craziness. Remember that the default mode in vi is "editing mode" with is actually where you type commands. The mode you call editing mode is actually insert mode and only applies for the duration of a command. Thus it is logical, from command mode, to enter a command, enter trext and then hit ESC to escape from insert mode back to the native editing/command mode. You have to get used to the idea that inserting text is not the default activity, navigating and changing text is - which is what most programmers do most of the time. So a command in vim consists of: <cmd key>[<type text to insert/change>[<escape>]] The good news about vim (as opposed to vi) is that you don't need to do that nearly as often since it recognises the arrow keys and you can do basic deletion etc while in insert mode. But the whole point of vi/vim is that you are required to change your way of thinking about text editing. It is a different approach in the same way that Lisp or Prolog or SQL are very different approaches to programming from Python. There is no escaping the fact that vi/vim are very powerful but only after you invest heavily in learning their ethos. Until you do they will drive you nuts! But if you use them regularly that only last a week or so... :-) HTH, Alan G From johanpo at googlemail.com Fri Aug 15 22:58:44 2008 From: johanpo at googlemail.com (Johan Nilsson) Date: Fri, 15 Aug 2008 22:58:44 +0200 Subject: [Tutor] RE expressions Message-ID: <op.ufx4j3z4dnj3wn@mu605418.rsint.net> Hi all python experts I am trying to work with BeautifulSoup and re and running into one problem. What I want to do is open a webpage and get some information. This is working fine I then want to follow some of links on this page and proces them. I manage to get links that I am interested in filtered out with by simple re expressions. My problem is that I now have a number of string that look like 'text "http:\123\interesting_adress\etc\etc\" more text' I have figured out that if it wasn't for the \ a simple p=re.compile('\"\w+\"') would do the trick. From what I understand \w only covers the set [a-zA-Z0-9_] and hence not the "\". I assume the solution is just in front of my eyes, and I have been looking on the screen for too long. Any hints would be appreciated. In [72]: p=re.compile('"\w+\"') In [73]: p.findall('asdsa"123abc123"jggfds') Out[73]: ['"123abc123"'] In [74]: p.findall('asdsa"123abc\123"jggfds') Out[74]: ['"123abcS"'] /Johan -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From steve at alchemy.com Fri Aug 15 23:41:11 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Aug 2008 14:41:11 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <g84p3n$5n8$1@ger.gmane.org> References: <mailman.15566.1218639544.920.tutor@python.org> <1218798858.6352.25.camel@lieryan-laptop> <g84p3n$5n8$1@ger.gmane.org> Message-ID: <48A5F7F7.4000906@alchemy.com> Alan Gauld wrote: > > "Lie Ryan" <lie.1296 at gmail.com> wrote > >> I've seen vi(m) being praised a lot, well, personally the thing that I >> hate the most about vim is its directional button (khjl) which is >> unnatural > > But very logical and easy to remember when you recall > that ^H was backspace (go left), and ^j was linefeed > (go down) and the typists home position has the right hand > on ,j,k,l, (and if you use your imagination K looks a bit like Not only that, but a lot of early terminals actually had arrow symbols printed on the h j k l keycaps, so no imagination necessary :) So a lot of it is tradition mixed with convenience (even if they're not strictly on the home positions, they're very easy and natural to get to as opposed to more mnemonic key bindings like ^P or ^N or whatever). Arrangements like wasz would probably have worked fine too but just didn't happen to. > Remember that the default mode in vi is "editing mode" with is actually > where you type commands. The mode you call editing mode is > actually insert mode and only applies for the duration of a command. > Thus it is logical, from command mode, to enter a command, enter trext > and then hit ESC to escape from insert mode back to the native > editing/command mode. You have to get used to the idea that inserting > text is not the default activity, navigating and changing text is - > which is > what most programmers do most of the time. So a command in > vim consists of: I guess this is where having come from TECO before learning vi paid off for me, so that was really ingrained by then :) > But the whole point of vi/vim is that you are required to change your > way of thinking about text editing. It is a different approach in the > same way that Lisp or Prolog or SQL are very different approaches > to programming from Python. There is no escaping the fact that > vi/vim are very powerful but only after you invest heavily in learning > their ethos. Until you do they will drive you nuts! But if you use > them regularly that only last a week or so... :-) And that's an excellent point with regard to languages too. Learning a new language is always a good thing to do if it changes how you look at programming. Only knowing how to edit text in one fashion with one tool makes as much sense as only knowing one way to write a program, in one language. --steve From steve at alchemy.com Fri Aug 15 23:46:33 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Aug 2008 14:46:33 -0700 Subject: [Tutor] RE expressions In-Reply-To: <op.ufx4j3z4dnj3wn@mu605418.rsint.net> References: <op.ufx4j3z4dnj3wn@mu605418.rsint.net> Message-ID: <48A5F939.8000502@alchemy.com> Johan Nilsson wrote: > 'text "http:\123\interesting_adress\etc\etc\" more text' Does this really use backslashes in the text? The standard for URLs (if that's what it is) is to use forward slashes. For your RE, though, you can always use [...] to specify a range including whatever you like. Remember that \ is a special symbol, too. If you want to match a literal \ character, the RE for that is \\. Also remember to use a raw string in Python so the string-building syntax doesn't get confused by the backslashes too. How about something along the lines of: re.compile(r'"[a-zA-Z0-9_\\]*"') but why constrain what may be between the quotes? re.compile(r'"[^"]*"') or even re.compile('".*?"') > > I have figured out that if it wasn't for the \ a simple > p=re.compile('\"\w+\"') would do the trick. From what I understand \w > only covers the set [a-zA-Z0-9_] and hence not the "\". > I assume the solution is just in front of my eyes, and I have been > looking on the screen for too long. Any hints would be appreciated. > > > In [72]: p=re.compile('"\w+\"') > > In [73]: p.findall('asdsa"123abc123"jggfds') > Out[73]: ['"123abc123"'] > > In [74]: p.findall('asdsa"123abc\123"jggfds') > Out[74]: ['"123abcS"'] > > /Johan > From steve at alchemy.com Sat Aug 16 00:01:46 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Aug 2008 15:01:46 -0700 Subject: [Tutor] RE expressions In-Reply-To: <48A5F939.8000502@alchemy.com> References: <op.ufx4j3z4dnj3wn@mu605418.rsint.net> <48A5F939.8000502@alchemy.com> Message-ID: <48A5FCCA.40105@alchemy.com> Steve Willoughby wrote: > Johan Nilsson wrote: >> In [74]: p.findall('asdsa"123abc\123"jggfds') >> Out[74]: ['"123abcS"'] By the way, you're confusing the use of \ in strings in general with the use of \ in regular expressions and the appearance of \ as a character in data strings encountered by your Python program. When you write the code: p.findall('asdsa"123abc\123"jggfds') the character string 'asdsa"123abc\123"jggfds' contains the special code \123 which means "the ASCII character with the octal value 123". That happens to be the letter S. So that's the same as if you had typed: p.findall('asdsa"123abcS"jggfds') which may explain your results. using a raw string would have solved that problem. From angelayian at yahoo.com Sat Aug 16 00:17:10 2008 From: angelayian at yahoo.com (Angela Yang) Date: Fri, 15 Aug 2008 15:17:10 -0700 (PDT) Subject: [Tutor] os.path.walk vs unix find command Message-ID: <202491.72665.qm@web50107.mail.re2.yahoo.com> Hi Python gurus: Is os.popen("find") faster or slower than os.path.walk to find file pattern in the directory tree?? I thought os.path.walk would be faster than unix find, but that doesn't seem to be the case? What is the fastest way in python to search for a file with a given pattern in a directory tree? Here's the code using os.path.walk: ? def find_src_mk_file(walk_lst_result, dirname, fnames): ? ??? x = len(dirname) ??? if (dirname[x-4:x] == "/src"): ??????? result = glob.glob(os.path.join(dirname, "src.mk")) ??????? if result: ??????????? walk_lst_result.append(result[0]) def is_makefile_outofdate(): ??? <code> ??????????? walk_lst_result = [] ??????????? os.path.walk( component_dir, find_src_mk_file, walk_lst_result ) ? ? ??????????? # check each src.mk and remove from lst ??????????? for sub_file_src_mk in walk_lst_result: ??? <code> Anything wrong with this code?? Please advise. Thanks. Angela -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080815/09158993/attachment.htm> From cfuller084 at thinkingplanet.net Sat Aug 16 03:29:46 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 15 Aug 2008 20:29:46 -0500 Subject: [Tutor] os.path.walk vs unix find command In-Reply-To: <202491.72665.qm@web50107.mail.re2.yahoo.com> References: <202491.72665.qm@web50107.mail.re2.yahoo.com> Message-ID: <200808152029.46802.cfuller084@thinkingplanet.net> On Friday 15 August 2008 17:17, Angela Yang wrote: > Hi Python gurus: > > > > Is os.popen("find") faster or slower than os.path.walk to find file pattern > in the > > directory tree?? I thought os.path.walk would be faster than unix find, but > that doesn't > > seem to be the case? > > > I'd expect find to be faster, its written in C, and probably optimized pretty well for its task. Less portable, however. > What is the fastest way in python to search for a file with a given pattern > in a directory > > tree? > > > > Here's the code using os.path.walk: > > ? > > def find_src_mk_file(walk_lst_result, dirname, fnames): > > ? > > ??? x = len(dirname) > > ??? if (dirname[x-4:x] == "/src"): This is a lot more than you need. You can index strings relative to the end with negative numbers, and if you leave the second half of the slice empty, it will go to the end. Similarly with the first half and starting from the beginning. You could have used dirname[-4:], but an even better way would be to just use the string method endswith(): dirname.endswith('/src'). You might also have used os..path.split()[1]=='src', which would have avoided portability issues. > > ??????? result = glob.glob(os.path.join(dirname, "src.mk")) You are duplicating effort here. The filenames are already in fnames, Search that list, rather than perform additional disk access. > > ??????? if result: > > ??????????? walk_lst_result.append(result[0]) > > def is_makefile_outofdate(): > > ??? <code> > > ??????????? walk_lst_result = [] > > ??????????? > os.path.walk( component_dir, find_src_mk_file, walk_lst_result ) > > ? ? > > ??????????? # check each src.mk and remove from lst > > ??????????? for sub_file_src_mk in walk_lst_result: > > ??? <code> > > > > Anything wrong with this code?? Please advise. > > > > Thanks. > > Angela That additional directory scan is your main problem. Cheers! From kent37 at tds.net Sat Aug 16 05:13:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Aug 2008 23:13:33 -0400 Subject: [Tutor] os.path.walk vs unix find command In-Reply-To: <202491.72665.qm@web50107.mail.re2.yahoo.com> References: <202491.72665.qm@web50107.mail.re2.yahoo.com> Message-ID: <1c2a2c590808152013o2e547254mfc54cdd622da5e39@mail.gmail.com> On Fri, Aug 15, 2008 at 6:17 PM, Angela Yang <angelayian at yahoo.com> wrote: > Hi Python gurus: > > Is os.popen("find") faster or slower than os.path.walk to find file pattern > in the > directory tree? I thought os.path.walk would be faster than unix find, but > that doesn't > seem to be the case? In general a mature (i.e. optimized) C program is going to be faster than a Python program to do the same task. > What is the fastest way in python to search for a file with a given pattern > in a directory > tree? > > Here's the code using os.path.walk: os.path.walk() is more-or-less obsolete, os.walk() does the same job and is much easier to use. I don't know if it is any faster though. If I understand your code, you want to find every file named src.mk that is in a directory named src. With os.walk() it would look like this: for dirpath, dirnames, filenames in os.walk(component_dir): if dirpath.endswith('/src'): if 'src.mk' in filenames: walk_lst_result.append(os.path.join(dirpath, 'src.mk') # or just handle the file here, no need to make the list Kent From eike.welk at post.rwth-aachen.de Sat Aug 16 00:41:19 2008 From: eike.welk at post.rwth-aachen.de (Eike Welk) Date: Sat, 16 Aug 2008 00:41:19 +0200 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> References: <515008f10808121129i599dfcdewd387654895797759@mail.gmail.com> <515008f10808121131g595f76efp53b35655da8633b2@mail.gmail.com> Message-ID: <200808160041.19776.eike.welk@post.rwth-aachen.de> On Tuesday 12 August 2008, Jaggo wrote: > Hello. > > I haven't much experience with programming. > > I'd like to point this question to programmers who write in editors > other than the default PyWin32: > > Why do you use your editor rather than using Pywin? What feature > has editor X got that PyWin hasn't? > (That is, other than "My editor runs on unix / linux"; while that > does count for something it is rather irrelevant to my current > situation.) > > Thanks in advance, > Omer. If you want to try out something basic, try Rope: http://rope.sourceforge.net/ropeide.html If has fairly good syntax completion and it is good in renaming everything (variables, classes, functions). It has also syntax coloring. However, it is ugly as hell, and the usability is horrible. It has no graphical debugger. I just read that it comes with EMACS keybindings, so you'll have to edit a configuration file to set it to something sane. It should run on Windows too, since it is written in pure Python. I really used it to write a small program. It is definitely usable. From steve at alchemy.com Sat Aug 16 05:17:49 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Aug 2008 20:17:49 -0700 Subject: [Tutor] os.path.walk vs unix find command In-Reply-To: <1c2a2c590808152013o2e547254mfc54cdd622da5e39@mail.gmail.com> References: <202491.72665.qm@web50107.mail.re2.yahoo.com> <1c2a2c590808152013o2e547254mfc54cdd622da5e39@mail.gmail.com> Message-ID: <48A646DD.1080107@alchemy.com> Kent Johnson wrote: >> Is os.popen("find") faster or slower than os.path.walk to find file pattern >> in the The general answer to "is find faster than os.[path.]walk faster" is "it depends." Find is optimized, compiled, and fast at what it does. However, what it does is somewhat limited. If you want to descend a filesystem doing anything complex along the way, it might be better to walk it from inside Python (or Perl or whatever) than to hook find up to other shell utilities or to create a pipe out from Python to find and back again. From joeturf at gmail.com Sat Aug 16 07:22:00 2008 From: joeturf at gmail.com (Joseph Bae) Date: Fri, 15 Aug 2008 22:22:00 -0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <g835eg$bjn$1@ger.gmane.org> References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> <g835eg$bjn$1@ger.gmane.org> Message-ID: <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> Thanks for the help! I have managed to get a good temperature converter program working! I am working on beefing it up a bit with some exception handling and an "and-or trick". The error handling works okay but I am having problems using and-or. Here's my updated code: def main(): true = 1 while true: try: temp = int(raw_input("Enter A Number : ")) break except ValueError: print "Invalid Input" while true: convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") if not convertTo == "F" and not convertTo == "C": print "Invalid Input" * else: convertTo == "C" and convertToCelsius(temp) or convertToFahrenheit(temp) break * def convertToCelsius(t): tC = (9.0/5.0) * (t - 32) print "%d Fahrenheit = %d Celsius" % (t, tC) def convertToFahrenheit(t): tF = (9.0/5.0) * (t + 32) print "%d Celsius = %d Fahrenheit" % (t, tF) if __name__=="__main__": main() Sample Output (as of right now): Enter A Number : 50 Convert to (F)ahrenheit or (C)elsius? C 50 Fahrenheit = 32 Celsius 32 Celsius = 147 Fahrenheit <-- shouldn't show up and 147 is too high ... This only happens when I tell it to convert to C, if I say F it works normally. I've debugged it with pdb.set_trace() many times but can't figure out what's wrong. Help is much appreciated =) Thanks, Joe On Thu, Aug 14, 2008 at 10:50 PM, Alan Gauld <alan.gauld at btinternet.com>wrote: > "Joseph Bae" <joeturf at gmail.com> wrote > > temp = input("Enter A Number : ") >> convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") >> >> if convertTo == "F": >> convertedTemp = convertToFahrenheit(temp) >> print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) >> else: >> convertedTemp = convertToCelsius(temp) >> print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) >> >> def convertToFahrenheit(t): >> tF = (9.0/5.0) * (t + 32) >> return tF >> >> def convertToCelsius(t): >> tC = (9.0/5.0) * (t - 32) >> return tC >> >> convertedTemp = convertToFahrenheit(temp) >> NameError: name 'convertToFahrenheit' is not defined >> >> This is most likely a very simple error, but can someone please clarify >> for >> me why it's behaving this way? >> > > Others have explained that you need to execute the function > definitions before Python sees the name. You can do this in > two ways depending on taste. > 1) As suggested move your main code below the function definitions. > 2) move your main code into a function - traditionally called main() > then call main as the last line of your code. > > The second method has two advantages: > 1) It maintains the top-down design style if thats your preferred style > 2) It makes it much easier to make the file into a reusable module. > > It has two minor disadvantages: > > 1) The extra function call (main() ) slows things down by a tiny amount > 2) the extra indentation level of being inside a function reduces the page > width slightly > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080815/9f2bf42b/attachment.htm> From joeturf at gmail.com Sat Aug 16 07:24:38 2008 From: joeturf at gmail.com (Joseph Bae) Date: Fri, 15 Aug 2008 22:24:38 -0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> <g835eg$bjn$1@ger.gmane.org> <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> Message-ID: <7bf8ebe60808152224n660778e3qac7523a5a910a99f@mail.gmail.com> Sorry! I copied the sample output from my command prompt incorrectly. Correct sample output: Enter A Number : 50 Convert to (F)ahrenheit or (C)elsius? C 50 Fahrenheit = 32 Celsius *50 *(not 32) Celsius = 147 Fahrenheit Joe On Fri, Aug 15, 2008 at 10:22 PM, Joseph Bae <joeturf at gmail.com> wrote: > Thanks for the help! > > I have managed to get a good temperature converter program working! I am > working on beefing it up a bit with some exception handling and an "and-or > trick". The error handling works okay but I am having problems using and-or. > Here's my updated code: > > def main(): > true = 1 > while true: > try: > temp = int(raw_input("Enter A Number : ")) > break > except ValueError: > print "Invalid Input" > while true: > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") > if not convertTo == "F" and not convertTo == "C": > print "Invalid Input" > * else: > convertTo == "C" and convertToCelsius(temp) or > convertToFahrenheit(temp) > break > * > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > print "%d Fahrenheit = %d Celsius" % (t, tC) > > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > print "%d Celsius = %d Fahrenheit" % (t, tF) > > if __name__=="__main__": > main() > > Sample Output (as of right now): > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? C > 50 Fahrenheit = 32 Celsius > 32 Celsius = 147 Fahrenheit <-- shouldn't show up and 147 is too high ... > > This only happens when I tell it to convert to C, if I say F it works > normally. I've debugged it with pdb.set_trace() many times but can't figure > out what's wrong. Help is much appreciated =) > > Thanks, > > Joe > > > On Thu, Aug 14, 2008 at 10:50 PM, Alan Gauld <alan.gauld at btinternet.com>wrote: > >> "Joseph Bae" <joeturf at gmail.com> wrote >> >> temp = input("Enter A Number : ") >>> convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") >>> >>> if convertTo == "F": >>> convertedTemp = convertToFahrenheit(temp) >>> print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) >>> else: >>> convertedTemp = convertToCelsius(temp) >>> print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) >>> >>> def convertToFahrenheit(t): >>> tF = (9.0/5.0) * (t + 32) >>> return tF >>> >>> def convertToCelsius(t): >>> tC = (9.0/5.0) * (t - 32) >>> return tC >>> >>> convertedTemp = convertToFahrenheit(temp) >>> NameError: name 'convertToFahrenheit' is not defined >>> >>> This is most likely a very simple error, but can someone please clarify >>> for >>> me why it's behaving this way? >>> >> >> Others have explained that you need to execute the function >> definitions before Python sees the name. You can do this in >> two ways depending on taste. >> 1) As suggested move your main code below the function definitions. >> 2) move your main code into a function - traditionally called main() >> then call main as the last line of your code. >> >> The second method has two advantages: >> 1) It maintains the top-down design style if thats your preferred style >> 2) It makes it much easier to make the file into a reusable module. >> >> It has two minor disadvantages: >> >> 1) The extra function call (main() ) slows things down by a tiny amount >> 2) the extra indentation level of being inside a function reduces the page >> width slightly >> >> HTH, >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.freenetpages.co.uk/hp/alan.gauld >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080815/b51e26ac/attachment.htm> From steve at alchemy.com Sat Aug 16 07:40:02 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Aug 2008 22:40:02 -0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> <g835eg$bjn$1@ger.gmane.org> <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> Message-ID: <48A66832.2040303@alchemy.com> Joseph Bae wrote: > Thanks for the help! > > I have managed to get a good temperature converter program working! I am > working on beefing it up a bit with some exception handling and an "and-or > trick". The error handling works okay but I am having problems using and-or. > Here's my updated code: > > def main(): > true = 1 > while true: > try: > temp = int(raw_input("Enter A Number : ")) > break > except ValueError: > print "Invalid Input" > while true: > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") > if not convertTo == "F" and not convertTo == "C": this might be easier to read as: if convertTo != "F" and convertTo != "C": or even: if convertTo not in ("F", "C"): > print "Invalid Input" > * else: > convertTo == "C" and convertToCelsius(temp) or > convertToFahrenheit(temp) I'd caution you against using and/or like this as a control flow pattern. It can be very confusing compared to this: if convertTo == "C": convertToCelsius(temp) else: convertToFahrenheit(temp) Note that the and/or pattern hides the bug you're facing. What you're really doing with the and/or pattern is this: if convertTo == "C": if not convertToCelsuis(temp): convertToFahrenheit(temp) else: convertToFahrenheit(temp) So what you had will call convertToCelsuis(temp) AND if that didn't return a true value, will ALSO call convertToFahrenheit(temp). Since convertToCelsius() doesn't return a value at all, that's exactly what happened. > break > * > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > print "%d Fahrenheit = %d Celsius" % (t, tC) > > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > print "%d Celsius = %d Fahrenheit" % (t, tF) That's not the correct calculation. C = (F - 32) / 1.8 F = (C * 1.8) + 32 > > if __name__=="__main__": > main() > > Sample Output (as of right now): > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? C > 50 Fahrenheit = 32 Celsius > 32 Celsius = 147 Fahrenheit <-- shouldn't show up and 147 is too high ... > > This only happens when I tell it to convert to C, if I say F it works > normally. I've debugged it with pdb.set_trace() many times but can't figure > out what's wrong. Help is much appreciated =) > > Thanks, > > Joe > > On Thu, Aug 14, 2008 at 10:50 PM, Alan Gauld <alan.gauld at btinternet.com>wrote: > >> "Joseph Bae" <joeturf at gmail.com> wrote >> >> temp = input("Enter A Number : ") >>> convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : ") >>> >>> if convertTo == "F": >>> convertedTemp = convertToFahrenheit(temp) >>> print "%d Celsius = %d Fahrenheit" % (temp, convertedTemp) >>> else: >>> convertedTemp = convertToCelsius(temp) >>> print "%d Fahrenheit = %d Celsius" % (temp, convertedTemp) >>> >>> def convertToFahrenheit(t): >>> tF = (9.0/5.0) * (t + 32) >>> return tF >>> >>> def convertToCelsius(t): >>> tC = (9.0/5.0) * (t - 32) >>> return tC >>> >>> convertedTemp = convertToFahrenheit(temp) >>> NameError: name 'convertToFahrenheit' is not defined >>> >>> This is most likely a very simple error, but can someone please clarify >>> for >>> me why it's behaving this way? >>> >> Others have explained that you need to execute the function >> definitions before Python sees the name. You can do this in >> two ways depending on taste. >> 1) As suggested move your main code below the function definitions. >> 2) move your main code into a function - traditionally called main() >> then call main as the last line of your code. >> >> The second method has two advantages: >> 1) It maintains the top-down design style if thats your preferred style >> 2) It makes it much easier to make the file into a reusable module. >> >> It has two minor disadvantages: >> >> 1) The extra function call (main() ) slows things down by a tiny amount >> 2) the extra indentation level of being inside a function reduces the page >> width slightly >> >> HTH, >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.freenetpages.co.uk/hp/alan.gauld >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From umeshsinghal at hotmail.co.uk Sat Aug 16 07:33:42 2008 From: umeshsinghal at hotmail.co.uk (Umesh Singhal) Date: Sat, 16 Aug 2008 06:33:42 +0100 Subject: [Tutor] For Loops and nested loops Message-ID: <BAY117-W2038EBB1B32FC8CD7FD730826C0@phx.gbl> Hi im still relatively new to python and i am designing a multiplication table that enables a user to input the size of the times table unfortunately ive stumbled on the nested loops this is what i have right now: a=raw_input('please enter a number') b=int(a) n=b+1 for row in range(1, n): for col in range(1, n): print "%3d " % (row * col), print the input which comes out is: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 however i need something more on the lines of: | 2 3 4 5 ================== 2 | 4 6 8 10 3 | 6 9 12 15 4 | 8 12 16 20 5 | 10 15 20 25 does anyone know what i need the third nested for loop to be ? to make it like the above example. Pleasee help me !! _________________________________________________________________ Win New York holidays with Kellogg?s & Live Search http://clk.atdmt.com/UKM/go/107571440/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/155bd5cb/attachment.htm> From kent37 at tds.net Sat Aug 16 13:31:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Aug 2008 07:31:27 -0400 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> References: <7bf8ebe60808141608t72dc60adg177b5dab7fcad247@mail.gmail.com> <g835eg$bjn$1@ger.gmane.org> <7bf8ebe60808152222v782a77bape757e46ef6ce5eba@mail.gmail.com> Message-ID: <1c2a2c590808160431o57afd077s95e91e62f16bdd69@mail.gmail.com> On Sat, Aug 16, 2008 at 1:22 AM, Joseph Bae <joeturf at gmail.com> wrote: > convertTo == "C" and convertToCelsius(temp) or > convertToFahrenheit(temp) This idiom has a pitfall. Consider A and B or C If B can evaluate to a false value, such as None or 0, the expression will not do what you intend. This idiom is only safe when you are sure that B will never evaluate to false. In Python 2.5 there is a better way to write it: B if A else C This is a safer way to write your program. Kent From lie.1296 at gmail.com Sat Aug 16 13:50:35 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 16 Aug 2008 18:50:35 +0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <mailman.17424.1218865216.920.tutor@python.org> References: <mailman.17424.1218865216.920.tutor@python.org> Message-ID: <1218887435.6352.82.camel@lieryan-laptop> On Sat, 2008-08-16 at 07:40 +0200, tutor-request at python.org wrote: > Message: 1 > Date: Fri, 15 Aug 2008 22:22:00 -0700 > From: "Joseph Bae" <joeturf at gmail.com> > Subject: Re: [Tutor] Beginner problem: name 'convertToFahrenheit' is > not defined > To: "Alan Gauld" <alan.gauld at btinternet.com> > Cc: tutor at python.org > Message-ID: > <7bf8ebe60808152222v782a77bape757e46ef6ce5eba at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Thanks for the help! > > I have managed to get a good temperature converter program working! I > am > working on beefing it up a bit with some exception handling and an > "and-or > trick". The error handling works okay but I am having problems using > and-or. > Here's my updated code: > You can fix some of these: > def main(): > true = 1 > while true: You can use True (note the capital (T)rue) for the boolean value of True. > try: > temp = int(raw_input("Enter A Number : ")) > break > except ValueError: > print "Invalid Input" Following the concept: Don't Make Me Repeat Myself, you could factor out the input function: def take_input(prompt, validator = int, errormessage = 'Invalid Input', exceptions = (ValueError, )): ''' prompt - String to be printed before raw_input validator - Function to be called after raw_input errormessage - String to be printed if any exceptions in exceptions is raised exceptions - List/Tuple containing list of exceptions to caught ''' while True: print prompt, try: return validator(raw_input()) except exceptions: print errormessage > while true: > convertTo = raw_input("Convert To (F)ahrenheit or (C)elsius? : > ") > if not convertTo == "F" and not convertTo == "C": If a boolean expression so simple looks complex, there is usually a simpler version. Try learning boolean logic a little bit, specifically boolean simplification for formal ways to simplify a boolean expression (although many text about boolean logic subject is from electronic, the basic rules are the same in programming and math). > print "Invalid Input" > * else: > convertTo == "C" and convertToCelsius(temp) or > convertToFahrenheit(temp) Never use and-or trick except if you're writing for Python Obfuscation Code Contest, they have huge pitfalls[1], the and-or trick was useful before python got "inline if" (although Guido choose a frankly rather unusual syntax): true_value if expression else false_value so your and-or trick should be: convertToCelcius(temp) if convertTo == 'C' else convertToFahrenheit(temp) [1] in and-or hackery a problem arises for codes like this: >>> b = 0 >>> c = 3 >>> True and b or c 3 >>> False and b or c 3 I'll leave it to you for brain exercise on why that thing happened > break > * > def convertToCelsius(t): > tC = (9.0/5.0) * (t - 32) > print "%d Fahrenheit = %d Celsius" % (t, tC) It's a bad idea for reusability to make convertToCelcius and convertToFahrenheit print the result themselves, the function would be more useful if it return the converted value and let the main program print them. This way, the function could be used for other things as well (for example, in a more complex temperature converter, rather than typing out all to all converters, it's a much better idea to convert to a common unit (say Kelvin, the SI standard for temperature), then convert it again to the target unit. This is impossible to be done if convertToCelcius prints the result themself. i.e.: def convertToCelcius(t): return #Do some formula t = 10 print '%s %s = %s %s' + (t, 'Fahrenheit', convertToCelcius(t), 'Celcius') > def convertToFahrenheit(t): > tF = (9.0/5.0) * (t + 32) > print "%d Celsius = %d Fahrenheit" % (t, tF) > > if __name__=="__main__": it's not a must, you should see PEP 8 (it's the style guideline): http://www.python.org/dev/peps/pep-0008/ > main() > > Sample Output (as of right now): > > Enter A Number : 50 > Convert to (F)ahrenheit or (C)elsius? C > 50 Fahrenheit = 32 Celsius > 32 Celsius = 147 Fahrenheit <-- shouldn't show up and 147 is too > high ... > > This only happens when I tell it to convert to C, if I say F it works > normally. I've debugged it with pdb.set_trace() many times but can't > figure > out what's wrong. Help is much appreciated =) > > Thanks, > > Joe From bgailer at gmail.com Sat Aug 16 16:27:17 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 16 Aug 2008 10:27:17 -0400 Subject: [Tutor] For Loops and nested loops In-Reply-To: <BAY117-W2038EBB1B32FC8CD7FD730826C0@phx.gbl> References: <BAY117-W2038EBB1B32FC8CD7FD730826C0@phx.gbl> Message-ID: <48A6E3C5.1090800@gmail.com> Umesh Singhal wrote: > Hi im still relatively new to python and i am designing a > multiplication table that enables a user to input the size of the > times table unfortunately ive stumbled on the nested loops this is > what i have right now: > > a=raw_input('please enter a number') > b=int(a) > n=b+1 > for row in range(1, n): > for col in range(1, n): > print "%3d " % (row * col), > print > > the input which comes out is: > 1 2 3 4 5 > 2 4 6 8 10 > 3 6 9 12 15 > 4 8 12 16 20 > 5 10 15 20 25 > > however i need something more on the lines of: > | 2 3 4 5 > ================== > 2 | 4 6 8 10 > 3 | 6 9 12 15 > 4 | 8 12 16 20 > 5 | 10 15 20 25 > > does anyone know what i need the third nested for loop to be ? to make > it like the above example. Pleasee help me !! I could write the program for you but I'd rather prod you into working it out yourself as I think you will learn more in the process. What code would you write to generate the first line? It is a loop, but not nested. At the beginning of each row you want to print the row number. What one statement would you add and where would you put it to do that. BTW I would find your questions and comments easier to read if you divided sentences with capitalization and punctuation. Be sure to reply-all. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From icetritlo at gmail.com Sat Aug 16 18:07:03 2008 From: icetritlo at gmail.com (Matti/Tritlo) Date: Sat, 16 Aug 2008 16:07:03 +0000 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <1218887435.6352.82.camel@lieryan-laptop> References: <mailman.17424.1218865216.920.tutor@python.org> <1218887435.6352.82.camel@lieryan-laptop> Message-ID: <aac792e80808160907l5ad5e739h695a3665b15a07e@mail.gmail.com> I too am a Beginner at python, and i have been playing around with it for about a week. While playing around, i decided to make a calculator program (A Very simple one) to calculate area and also to convert farenheit to celcius and vice versa. So, here is the code: def options(): print "Options:" print " 'p' to print options" print " 's' for area of square" print " 't' for area of triangle" print " 'c' for area of square" print " 'ce' to convert from celsius to farenheit" print " 'fa' to convert from fahrenheit to celcius" print " 'q' to quit the program" print "Welcome to this calculator." user = raw_input("So, What is your name? ") print "Oh, Welcome ", user,",I?ll be your calculator to day." print "Please select one of these options, and lets calculate!" print options() def positive(): print "Must be a positive number" def square_area(width, height): return width * height def triangle_area(width, height): return width * height / 2 def circle_area (radius): return radius * 3.141562953589793 def c_to_f(c_temp): return 9.0 / 5.0 * c_temp + 32 def f_to_c(f_temp): return (f_temp - 32.0) * 5.0 / 9.0 def choice(): choice = "p" while choice != "q": choice = raw_input("Option: ") if choice == "p": print options() elif choice == "s": print "So, you have chosen to calculate the area of a Square." w = input("Please enter Width: ") while w <= 0: positive() w = input("Please enter Width: ") h = input("Please enter Height: ") while h <= 0: positive() h = input("Please enter Height: ") print "The Square?s area is: ", square_area(w,h) elif choice == "t": print "So, you have chosen to calculate the area of a Triangle." w = input("Please enter Width: ") while w <= 0: positive() w = input("Please enter Width: ") h = input("Please enter Height: ") while h <= 0: positive() h = input("Please enter Height: ") print "The Triangle?s area is: ", triangle_area(w,h) elif choice == "c": print "So, you have chosen to calculate the area of a Circle." r = input("Please enter radius: ") while r <= 0: positive () r = input("Please enter radius: ") print "The Circle?s area is: ", circle_area (r) elif choice == "ce": print "So, you?re wondering how Celcius relates to Farenheit." c = input("Please enter Celcius degree?s: ") print c, "Degree?s Celcius are", c_to_f(c), "Degree?s Farenheit." elif choice == "fa": print "So, you?re wondering how Farenheit relates to Celcius." f = input("Please enter Farenheit degree?s: ") print f,"Degree?s Farenheit are", f_to_c(f), "Degree?s Celcius." else: print "That option does not exsist" choice = raw_input("Option: ") choice() print "Leaving eh, Well, Goodbye!" time.sleep(5) There you can see the Farenheit - Celcius part, and also the simple menu system. Hope this Helps! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/ef8d68ee/attachment-0001.htm> From lie.1296 at gmail.com Sat Aug 16 18:07:19 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 16 Aug 2008 23:07:19 +0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <mailman.17249.1218833940.920.tutor@python.org> References: <mailman.17249.1218833940.920.tutor@python.org> Message-ID: <1218902839.6352.141.camel@lieryan-laptop> > Message: 6 > Date: Fri, 15 Aug 2008 21:31:51 +0100 > From: "Alan Gauld" <alan.gauld at btinternet.com> > Subject: Re: [Tutor] What has Editor X got that PyWin32 hasn't? > To: tutor at python.org > Message-ID: <g84p3n$5n8$1 at ger.gmane.org> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Lie Ryan" <lie.1296 at gmail.com> wrote > > > I've seen vi(m) being praised a lot, well, personally the thing > that > > I > > hate the most about vim is its directional button (khjl) which is > > unnatural > > But very logical and easy to remember when you recall > that ^H was backspace (go left), and ^j was linefeed > (go down) and the typists home position has the right hand > on ,j,k,l, (and if you use your imagination K looks a bit like > an up arrow and L like a right facing symbol - but personally > I think that's coincidental!) and shifting one position left is > an easy reach. (BTW A lot of early terminal games, especially > on Unix use the hjkl format. And so, of course does the > bash shell and more (and maybe less?) ) No offense (to you and to other vi(m) fans), but that argument is forcing itself way too much[1], humans doesn't think in such terms -- not in their subconsciousness -- humans think visually when navigating (up is located somewhere higher than down)[2]. [1] (to note: it isn't that I don't remember the buttons, but I found myself subconsciously pressing j when I want to go up and k when I want to go down nearly all the time) [2] That's why no TV remote put their buttons in this arrangements: right down up left Though I do admit that plane pilots do have their own queerness on choosing the direction their plane goes when they move their joystick, somehow it does feels more natural. > > touchpad and keyboard 2) the keyboard is smaller, 3) many of the > > hotkeys > > require pressing Esc first to get out from editing/inserting mode, > > which > > is just as inconvenient as reaching the Ctrl. And for vi(m), after > > going > > to command/shortcut mode and pressing the shortcut, then most of the > > time you have to go back to editing mode by pressing i/a/etc, that > > is > > much worse than the Ctrl craziness. > > Remember that the default mode in vi is "editing mode" with is > actually OK, wrong terminology, I'm not too much fan of vi(m) myself, pardon for that. > where you type commands. The mode you call editing mode is > actually insert mode and only applies for the duration of a command. > Thus it is logical, from command mode, to enter a command, enter trext > and then hit ESC to escape from insert mode back to the native > editing/command mode. You have to get used to the idea that inserting > text is not the default activity, navigating and changing text is - > which is To me, as a programmer, navigating, inserting, deleting, and editing are four basic operation when editing a text, I can't stand inserting and deleting (or any one of them) being called second to the others. Why do they think that programmers insert texts less often than changing text? I'm not sure, probably that's their workflow. > what most programmers do most of the time. So a command in > vim consists of: > > <cmd key>[<type text to insert/change>[<escape>]] which is a waste of movement compared to modern text editor. Compared to just clicking then typing, pressing command then typing then escape is redundant. For those that used vim because you don't want your hand to be getting back and forth from the keyboard to mouse when typing, you should change to a laptop, in which the distance between the touchpad and keyboard is really close (you could, sort of, say that the keyboard and the touchpad is a singular device). I could even argue that moving the hand from the home position to touchpad is shorter than moving the hand from home position to Esc key, which you have to do many times in vim. And as an addition, in a modern text editor, you could use shift+directional[1] to select text very quickly, you can't do that in the almighty vim, you must instead type "y(ank)-an_obscure_direction_that_is_slow_to_work_with_because_you_have_to_carefully_count_first_how_many_characters_or_words_or_lines_you_want_to_yank_,_what_makes_it_worse_is_you_cannot_realize_counting_mistake_until_you_putted_the_text_,_also_if_you_make_a_mistake_you_have_to_do_it_from_beginning_instead_of_continuing_where_you_left_off_before-ESCAPE(From_this_mess)" [1] directional isn't only up, down, left, and right, but also home, end, page up, page down, and ctrl+directional, most people never fully utilize the extended directionals and instead uses the mouse (or in case of vim users, keyboards) more than is really necessary (instead of balancing between keyboard and mouse usage). > The good news about vim (as opposed to vi) The only good news about vim is it's the only command-line text editor in my OS that I know. > is that you don't > need to do that nearly as often since it recognises the arrow > keys and you can do basic deletion etc while in insert mode. I know I can use the arrow key, but that doesn't seems to be the preferred choice of vim-ers when they're in editing mode (now with correct terminology) > But the whole point of vi/vim is that you are required to change your > way of thinking about text editing. It is a different approach in the > same way that Lisp or Prolog or SQL are very different approaches > to programming from Python. Although I never used Prolog and only knows the basic syntax for Lisp (when I had the time I will surely approach them), I never thought SQL as a programming language, I thought it deserve a classification of its own kind, just like HTML (to me HTML/XML is Data Descriptor Language, and SQL is ). > There is no escaping the fact that > vi/vim are very powerful I agree it is very powerful, at its time, when computers are keyboard-only and terminal-only. But now, most of its power is largely redundant and is pale compared to modern text-editor that do acknowledge mouse as a primary input device. > but only after you invest heavily in learning > their ethos. Until you do they will drive you nuts! But if you use > them regularly that only last a week or so... :-) > HTH, > > Alan G From srilyk at gmail.com Sat Aug 16 18:20:38 2008 From: srilyk at gmail.com (W W) Date: Sat, 16 Aug 2008 11:20:38 -0500 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <1218902839.6352.141.camel@lieryan-laptop> References: <mailman.17249.1218833940.920.tutor@python.org> <1218902839.6352.141.camel@lieryan-laptop> Message-ID: <333efb450808160920j306b85a0l5ba85ca8d5345656@mail.gmail.com> On Sat, Aug 16, 2008 at 11:07 AM, Lie Ryan <lie.1296 at gmail.com> wrote: > > I agree it is very powerful, at its time, when computers are > keyboard-only and terminal-only. But now, most of its power is largely > redundant and is pale compared to modern text-editor that do acknowledge > mouse as a primary input device. > I've never met anyone who could edit faster with a mouse than I can with my basic knowledge of vi. Bottom line - you don't like to use vi (or prefer to use your mouse). Those of us who use vi have experienced its benefits. (And using visual mode to yank helps eliminate counting errors ;) ) Neither of us will change, and making arguments to the contrary is worse than arguing about religion (although one could very well argue that choice of editors is practically a religion, and I'm sure there are many folks out there who defend their editor more than their religion). Bottom line v.2, People should use what works best for them. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/f535fca8/attachment.htm> From kent37 at tds.net Sat Aug 16 18:40:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Aug 2008 12:40:19 -0400 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <aac792e80808160907l5ad5e739h695a3665b15a07e@mail.gmail.com> References: <mailman.17424.1218865216.920.tutor@python.org> <1218887435.6352.82.camel@lieryan-laptop> <aac792e80808160907l5ad5e739h695a3665b15a07e@mail.gmail.com> Message-ID: <1c2a2c590808160940y1f96b7f3m58ac2f81622374af@mail.gmail.com> On Sat, Aug 16, 2008 at 12:07 PM, Matti/Tritlo <icetritlo at gmail.com> wrote: Some quick notes: > print options() No need for the 'print' here, options() already prints. The extra print will print the return value of options(), which is None. > def triangle_area(width, height): > return width * height / 2 This will give an incorrect result if width and height are both odd integers. Use 2.0 instead of 2 to force float division. Kent From kent37 at tds.net Sat Aug 16 18:45:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Aug 2008 12:45:50 -0400 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <1218902839.6352.141.camel@lieryan-laptop> References: <mailman.17249.1218833940.920.tutor@python.org> <1218902839.6352.141.camel@lieryan-laptop> Message-ID: <1c2a2c590808160945t1c3353f1m281008f18135d4cf@mail.gmail.com> This is getting pretty far off topic. Let's not have an editor flamewar please. If you like vim, great! Use it! If you don't like vim, great! Use something else. If everyone liked the same editor features there wouldn't be so many to choose from. Thanks, Kent From lie.1296 at gmail.com Sat Aug 16 19:16:13 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 17 Aug 2008 00:16:13 +0700 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <aac792e80808160907l5ad5e739h695a3665b15a07e@mail.gmail.com> References: <mailman.17424.1218865216.920.tutor@python.org> <1218887435.6352.82.camel@lieryan-laptop> <aac792e80808160907l5ad5e739h695a3665b15a07e@mail.gmail.com> Message-ID: <1218906973.6352.198.camel@lieryan-laptop> On Sat, 2008-08-16 at 16:07 +0000, Matti/Tritlo wrote: > I too am a Beginner at python, and i have been playing around with it > for about a week. While playing around, i decided to make a calculator > program (A Very simple one) to calculate area and also to convert > farenheit to celcius and vice versa. So, here is the code: Shall I give some comments on your code? > def options(): > print "Options:" > print " 'p' to print options" > print " 's' for area of square" > print " 't' for area of triangle" > print " 'c' for area of square" > print " 'ce' to convert from celsius to farenheit" > print " 'fa' to convert from fahrenheit to celcius" > print " 'q' to quit the program" > print "Welcome to this calculator." > user = raw_input("So, What is your name? ") > print "Oh, Welcome ", user,",I?ll be your calculator to day." > print "Please select one of these options, and lets calculate!" > print options() > def positive(): > print "Must be a positive number" > > def square_area(width, height): > return width * height > > def triangle_area(width, height): > return width * height / 2 > > def circle_area (radius): > return radius * 3.141562953589793 > > def c_to_f(c_temp): > return 9.0 / 5.0 * c_temp + 32 > > def f_to_c(f_temp): > return (f_temp - 32.0) * 5.0 / 9.0 > > def choice(): > choice = "p" > while choice != "q": > choice = raw_input("Option: ") > if choice == "p": > print options() > elif choice == "s": > print "So, you have chosen to calculate the area of a > Square." > w = input("Please enter Width: ") never use input(), use raw_input() instead. input() parses the string it receives first, and may (read: WILL in the hands of certain persons) allow user to input certain strings that get parsed into dangerous codes. Use int(raw_input()) instead to convert the result of raw_input (i.e. string) into a number (i.e. integer). Since we're using int() to convert the string into number now, if you typed non-numbers, you'd get an Exception/Error, so you should add a try: block that would -- in case of errors -- reask the user again. try: int('string') except ValueError: print 'You passed a string that cannot be turned into integer' > while w <= 0: > positive() > w = input("Please enter Width: ") > h = input("Please enter Height: ") > while h <= 0: > positive() > h = input("Please enter Height: ") > print "The Square?s area is: ", square_area(w,h) > elif choice == "t": > print "So, you have chosen to calculate the area of a > Triangle." > w = input("Please enter Width: ") > while w <= 0: > positive() > w = input("Please enter Width: ") > h = input("Please enter Height: ") > while h <= 0: > positive() > h = input("Please enter Height: ") > print "The Triangle?s area is: ", triangle_area(w,h) Don't you think that all those codes seems very similar and redundant and tiring to type? Then make it into a function, pass arguments to make the behavior of the function differs and cut short a lot of lines. def getanumber(prompt): h = int(raw_input(prompt)) while h <= 0: positive() h = int(raw_input(prompt)) return h ... elif choice == 't': print "So, you have chosen to calculate the area of a Triangle." w = getanumber("Please enter Width: ") h = getanumber("Please enter Height: ") print "The Triangle?s area is: ", triangle_area(w,h) elif choice ... Ok, now we're left with that, which is still redundant since the pattern of print, get input values, and print output values is still repeated. Personally I'd go even further to make them functions too, but I'll let you pass with that (why? because: since not all menu options require the same number of argument it'd require using a clever trick involving list/dictionary and for-loop iteration, for now I think it might be out of bounds). PS: If you're really interested in how your program can still even be made more concise and less redundant, see way below for a raw, uncommented, !untested! code. > > elif choice == "c": > print "So, you have chosen to calculate the area of a > Circle." > r = input("Please enter radius: ") > while r <= 0: > positive () > r = input("Please enter radius: ") > print "The Circle?s area is: ", circle_area (r) > elif choice == "ce": > print "So, you?re wondering how Celcius relates to > Farenheit." > c = input("Please enter Celcius degree?s: ") > print c, "Degree?s Celcius are", c_to_f(c), "Degree?s > Farenheit." > elif choice == "fa": > print "So, you?re wondering how Farenheit relates to > Celcius." > f = input("Please enter Farenheit degree?s: ") > print f,"Degree?s Farenheit are", f_to_c(f), "Degree?s > Celcius." > > else: > print "That option does not exsist" > choice = raw_input("Option: ") > choice() > print "Leaving eh, Well, Goodbye!" > time.sleep(5) > > There you can see the Farenheit - Celcius part, and also the simple > menu system. > > Hope this Helps! > > formulas = { 's': ( 'Square Area', ('Please enter Width: ', 'Please enter Height: '), square_area, ), 't': ( 'Triangle Area', ('Please enter Width: ', 'Please enter Height: '), triangle_area, ), 'c': ( 'Circle Area', ('Please enter Radius: ',), circle_area, ), # etc } def getanumber(prompt): h = int(raw_input(prompt)) while h <= 0: positive() h = int(raw_input(prompt)) return h def takeinputandcalculate(prompts, func): # got to choose a better, shorter name fargs = [] for prompt in prompts: fargs.append(getanumber(prompt)) return func(*fargs) choice = raw_input('choose option [s, t, c]: ') name, prompts, func = formulas[choice] print 'So you have chosen to calculate %s' % name result = takeinputandcalculate(prompts, func) print 'That %s is %s' % (name, result) From lie.1296 at gmail.com Sat Aug 16 19:29:23 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 17 Aug 2008 00:29:23 +0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <333efb450808160920j306b85a0l5ba85ca8d5345656@mail.gmail.com> References: <mailman.17249.1218833940.920.tutor@python.org> <1218902839.6352.141.camel@lieryan-laptop> <333efb450808160920j306b85a0l5ba85ca8d5345656@mail.gmail.com> Message-ID: <1218907763.6352.210.camel@lieryan-laptop> On Sat, 2008-08-16 at 11:20 -0500, W W wrote: > On Sat, Aug 16, 2008 at 11:07 AM, Lie Ryan <lie.1296 at gmail.com> wrote: > > > I agree it is very powerful, at its time, when computers are > keyboard-only and terminal-only. But now, most of its power is > largely > redundant and is pale compared to modern text-editor that do > acknowledge > mouse as a primary input device. > > I've never met anyone who could edit faster with a mouse than I can > with my basic knowledge of vi. I think the greatest bottleneck in editing isn't the tool itself, but how fast the editor can identify what to edit/write next (the slowest thing attached to a computer is between the keyboard and chair). And if you're doing an editing contest, I'm sure I can fare _at_least_ as fast as you. > Bottom line - you don't like to use vi (or prefer to use your mouse). Don't take it wrong, I don't hate vi, I like to use it too in certain circumstances, I only thought it was way too overrated. > Those of us who use vi have experienced its benefits. (And using > visual mode to yank helps eliminate counting errors ;) ) > > Neither of us will change, and making arguments to the contrary is > worse than arguing about religion (although one could very well argue > that choice of editors is practically a religion, and I'm sure there > are many folks out there who defend their editor more than their > religion). > > Bottom line v.2, People should use what works best for them. > I won't try to change you if you won't. I agree with you though: "choose what's works best for you". For me: touchpad+keyboard combination allows the fastest editing speed a typical vim-ers would have a hard time to match. > -Wayne > From steve at alchemy.com Sat Aug 16 19:35:31 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 16 Aug 2008 10:35:31 -0700 Subject: [Tutor] For Loops and nested loops In-Reply-To: <BAY117-W2038EBB1B32FC8CD7FD730826C0@phx.gbl> References: <BAY117-W2038EBB1B32FC8CD7FD730826C0@phx.gbl> Message-ID: <20080816173531.GA23065@dragon.alchemy.com> On Sat, Aug 16, 2008 at 06:33:42AM +0100, Umesh Singhal wrote: > Hi im still relatively new to python and i am designing a multiplication table that enables a user to input the size of the times table unfortunately ive stumbled on the nested loops this is what i have right now: Is this a homework assignment? Forgive me if it's not, but somehow it feels like the sort of thing a teacher would assign. At least, I've been known to give my programming students things like it before when they were just starting out. > a=raw_input('please enter a number') > b=int(a) > n=b+1 > for row in range(1, n): remember what <n> means in range(1, <n>). You may have a fencepost error (off-by-one), depending on what you intended to happen here. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From lie.1296 at gmail.com Sat Aug 16 19:39:40 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 17 Aug 2008 00:39:40 +0700 Subject: [Tutor] For Loops and nested loops In-Reply-To: <mailman.17556.1218902833.920.tutor@python.org> References: <mailman.17556.1218902833.920.tutor@python.org> Message-ID: <1218908380.6352.218.camel@lieryan-laptop> On Sat, 2008-08-16 at 18:07 +0200, tutor-request at python.org wrote: > Message: 1 > Date: Sat, 16 Aug 2008 06:33:42 +0100 > From: Umesh Singhal <umeshsinghal at hotmail.co.uk> > Subject: [Tutor] For Loops and nested loops > To: <tutor at python.org> > Message-ID: <BAY117-W2038EBB1B32FC8CD7FD730826C0 at phx.gbl> > Content-Type: text/plain; charset="windows-1252" > > > Hi im still relatively new to python and i am designing a > multiplication table that enables a user to input the size of the > times table unfortunately ive stumbled on the nested loops this is > what i have right now: > > a=raw_input('please enter a number') > b=int(a) > n=b+1 > for row in range(1, n): > for col in range(1, n): > print "%3d " % (row * col), > print > > the input which comes out is: > 1 2 3 4 5 > 2 4 6 8 10 > 3 6 9 12 15 > 4 8 12 16 20 > 5 10 15 20 25 > > however i need something more on the lines of: > | 2 3 4 5 > ================== > 2 | 4 6 8 10 > 3 | 6 9 12 15 > 4 | 8 12 16 20 > 5 | 10 15 20 25 > > does anyone know what i need the third nested for loop to be ? to make > it like the above example. Pleasee help me !! You don't need to use third nested loop, your two nested loop is enough. First, however, you need to think first, how you'd generate the output. Following your thinking pattern, I'd do it like this: #1 | 2 3 4 5 #2 | 2 3 4 5 ================== 2 | #3 | 2 3 4 5 ================== 2 | 4 #4 | 2 3 4 5 ================== 2 | 4 6 #5 | 2 3 4 5 ================== 2 | 4 6 8 #6 | 2 3 4 5 ================== 2 | 4 6 8 10 #7 | 2 3 4 5 ================== 2 | 4 6 8 10 3 | #8 etc Do you see how you could generate the table headings? From emadnawfal at gmail.com Sat Aug 16 19:55:36 2008 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Sat, 16 Aug 2008 13:55:36 -0400 Subject: [Tutor] simple python scrip for collocation discovery Message-ID: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> Hello Tutors, I'm trying to write a small scrip to find collocations using chi squared, depending on a fairly big corpus. The program below does a good job, but it's too slow, and I need to process something like 50 million words. How can I make it run fast? Your help is appreciated. Emad nawfal #! usr/bin/python # Chi-squared collocation discovery # Important definitions first. Let's suppose that we # are trying to find whether "powerful computers" is a collocation # N = The number of all bigrams in the corpus # O11 = how many times the bigram "powerful computers" occurs in the corpus # O22 = the number of bigrams not having either word in our collocation = N - O11 # O12 = The number of bigrams whose second word is our second word # but whose first word is not "powerful" # O21 = The number of bigrams whose first word is our first word, but whose second word # is different from oour second word ########################################################### print """ ************************************************* * Welcome to the Collocationer * * * * ************************************************* """ # Let's first get the text and turn into bigrams bigrams = [] infile = file("corpus.txt") text = infile.read().lower().split() infile.close() for i,v in enumerate(text): # get words and their ranking number if i < len(text)-1: # This guarntees that the list index is not out of range bigram = v, text[i+1] # each word and the two succeding words bigrams.append(bigram) tested_collocate = raw_input("Enter the bigram you think is a collocation\n") word1 = tested_collocate.split()[0] word2 = tested_collocate.split()[1] N = len(bigrams) O11 = bigrams.count(tuple(tested_collocate.split())) O22 = [bigram for bigram in bigrams if word1 != bigram[0] and word2 != bigram[1]] O12 = [bigram for bigram in bigrams if bigram[1] == word2 and bigram[0] != word1] O21 = [bigram for bigram in bigrams if bigram[0]== word1 and bigram[1] != word2] O22 = len(O22) O12 = len(O12) O21 = len(O21) chi2 = (N * ((O11 * O22 - O12 * O21) ** 2))/ float((O11 + O12) * (O11 + O21) * (O12 + O22) * (O21 + O22)) print "Chi-Squared = ", chi2 if chi2 > 3.841: print "These two words form a collocation" else: print "These two words do not form a collocation" raw_input('Enter to Exit') -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/df614156/attachment.htm> From steve at alchemy.com Sat Aug 16 20:09:23 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 16 Aug 2008 11:09:23 -0700 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> Message-ID: <20080816180923.GB23065@dragon.alchemy.com> On Sat, Aug 16, 2008 at 01:55:36PM -0400, Emad Nawfal (???? ????) wrote: > Hello Tutors, > I'm trying to write a small scrip to find collocations using chi squared, Minor nit, but the word you're looking for here is "script". "Scrip" is also an English word but means something completely different. Looking professional in a field includes using the jargon correctly. > depending on a fairly big corpus. > The program below does a good job, but it's too slow, and I need to process > something like 50 million words. > How can I make it run fast? How fast is fast enough? What's its time now? Can you identify where it might be slowing down? Depending on the order of magnitude of the speedup you're looking to achieve, the answer could be very different. > # Let's first get the text and turn into bigrams > bigrams = [] > infile = file("corpus.txt") > text = infile.read().lower().split() This strikes me as needlessly memory-consuming. You might want to iterate over lines of text instead of sucking the entire file into a giant string. I'm guessing you want to recognize words next to one another even if separated by a newline? Be aware of the cost, though, of passing potentially huge data values around. > infile.close() > for i,v in enumerate(text): # get words and their ranking number > if i < len(text)-1: # This guarntees that the list index is not out of > range > bigram = v, text[i+1] # each word and the two succeding words > bigrams.append(bigram) Why don't you trust enumerate's i values, out of curiosity? It seems to me if you think of what you're collecting here you could do some calculating on the fly as you look through the list of words and wouldn't need to be building these lists and then going back through them. I'm trying to give some vague help without doing the work for you because we don't do homework exercises for people :) -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From john.destefano at gmail.com Sat Aug 16 20:15:53 2008 From: john.destefano at gmail.com (John DeStefano) Date: Sat, 16 Aug 2008 14:15:53 -0400 Subject: [Tutor] python-ldap installation Message-ID: <f2160e0d0808161115ge0151f9n8101896a6b7d8dc9@mail.gmail.com> This may sound silly, but I've been searching for a reliable method for installing the python-ldap module for Python 2.4 in a Windows XP environment. Actually, I'm looking for a method that would work cross-platform with Linux and OS X as well, or at least methods that were close enough in nature to be called similar. As far as Windows goes: I've tried installing the binary linked from the python-ldap project page, but that is a third-party binary, and they only have installers for 2.5 (I tried these just to be sure, and sure enough, 2.4 won't import the module, as it wants a 2.5 DLL instead). I did find a binary elsewhere that someone created [1], but this one seems fairly outdated. Ultimately, I'd like to automate an installation method as part of a buildout environment script that could work on multiple platforms, but I'm not sure that's going to be possible: Windows doesn't use apt-get, OS X doesn't use DLL files, etc. I also found this post [2], which probably works for systems that use apt-get, but not for others, and seems fairly complicated as well. Thanks in advance for your ideas and pointers on whether this is possible, or the best way to do it on different platforms. ~John [1] http://www.agescibs.org/mauro/ [2] http://bluedynamics.com/articles/jens/python-ldap-as-egg-with-buildout From emadnawfal at gmail.com Sat Aug 16 20:20:04 2008 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Sat, 16 Aug 2008 14:20:04 -0400 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <20080816180923.GB23065@dragon.alchemy.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> <20080816180923.GB23065@dragon.alchemy.com> Message-ID: <652641e90808161120j12add28cv108838228baab9f5@mail.gmail.com> Dear Steve, Thank you so much for your help. Actually this is not homework. It's gonna be used in building a collocation dictionary as part of my dissertation. Please remeber that I'm not a programmer, so many of the terminologies may not be accessible to me. Thank you also for attracting my attention to the typo On Sat, Aug 16, 2008 at 2:09 PM, Steve Willoughby <steve at alchemy.com> wrote: > On Sat, Aug 16, 2008 at 01:55:36PM -0400, Emad Nawfal (???? ????) wrote: > > Hello Tutors, > > I'm trying to write a small scrip to find collocations using chi squared, > > Minor nit, but the word you're looking for here is "script". "Scrip" > is also an English word but means something completely different. > Looking professional in a field includes using the jargon correctly. > > > depending on a fairly big corpus. > > The program below does a good job, but it's too slow, and I need to > process > > something like 50 million words. > > How can I make it run fast? > > How fast is fast enough? > What's its time now? > Can you identify where it might be slowing down? > > Depending on the order of magnitude of the speedup you're looking > to achieve, the answer could be very different. > > > # Let's first get the text and turn into bigrams > > bigrams = [] > > infile = file("corpus.txt") > > text = infile.read().lower().split() > > This strikes me as needlessly memory-consuming. You might want to > iterate over lines of text instead of sucking the entire file into > a giant string. I'm guessing you want to recognize words next to > one another even if separated by a newline? Be aware of the cost, > though, of passing potentially huge data values around. > > > infile.close() > > for i,v in enumerate(text): # get words and their ranking number > > if i < len(text)-1: # This guarntees that the list index is not out > of > > range > > bigram = v, text[i+1] # each word and the two succeding words > > bigrams.append(bigram) > > Why don't you trust enumerate's i values, out of curiosity? > > It seems to me if you think of what you're collecting here > you could do some calculating on the fly as you look through > the list of words and wouldn't need to be building these > lists and then going back through them. > > I'm trying to give some vague help without doing the work for you > because we don't do homework exercises for people :) > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/a4dc1791/attachment.htm> From srilyk at gmail.com Sat Aug 16 20:37:55 2008 From: srilyk at gmail.com (W W) Date: Sat, 16 Aug 2008 13:37:55 -0500 Subject: [Tutor] python-ldap installation In-Reply-To: <f2160e0d0808161115ge0151f9n8101896a6b7d8dc9@mail.gmail.com> References: <f2160e0d0808161115ge0151f9n8101896a6b7d8dc9@mail.gmail.com> Message-ID: <333efb450808161137yaeda547o58b0f335ed026efd@mail.gmail.com> On Sat, Aug 16, 2008 at 1:15 PM, John DeStefano <john.destefano at gmail.com>wrote: > > Ultimately, I'd like to automate an installation method as part of a > buildout environment script that could work on multiple platforms, but > I'm not sure that's going to be possible: Windows doesn't use apt-get, > OS X doesn't use DLL files, etc. I also found this post [2], which > probably works for systems that use apt-get, but not for others, and > seems fairly complicated as well. > > Thanks in advance for your ideas and pointers on whether this is > possible, or the best way to do it on different platforms. For the most part I doubt I'd be much help, but if you're looking for a way to work cross-platform, you have a few options. 1) Package all the installers together, and use your script to determine the system, either by user input, or by looking for a file that should exist on the system. It might be safer to ask for user confirmation in that case, though. 2) Do the same thing, but instead of packaging all the files, retrieve them from the 'net. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/8c2c28e0/attachment.htm> From alan.gauld at btinternet.com Sat Aug 16 23:42:55 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Aug 2008 22:42:55 +0100 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? References: <mailman.17249.1218833940.920.tutor@python.org> <1218902839.6352.141.camel@lieryan-laptop> Message-ID: <g87hkv$n84$1@ger.gmane.org> "Lie Ryan" <lie.1296 at gmail.com> wrote > No offense (to you and to other vi(m) fans), No offense taken, as I said right at the beginning of this thread, editors are a religious battleground for programmers and elicit very personal reactions. Personally I use over a dozen editors on a regular basis but only about 3 or 4 heavily - all of which are quite different in style. > not in their subconsciousness -- humans think visually when > navigating > (up is located somewhere higher than down)[2]. Actually humans think in lots of different ways. Programmers tend not to think visually but verbally (or more accuratelty symbolically) which is one reason so called visual programming environments have failed to take off! > [2] That's why no TV remote put their buttons in this arrangements: Some do, I used to own one (a Philips as I recall)! :-) > they think that programmers insert texts less often than changing > text? > I'm not sure, probably that's their workflow. It's not so much "changing" its navigating. Studies have shown that programmers spend most of their time going back over code they have alrweady written (or someone else has) and making small changes. Thats exactly where vi/vim excels. In fact when I used to work exclusively on Unix I used emacs for the initial text creation (because it is better at that) but then used vi (actually viper mode in Xemacs) for editing changes thereafter. The best of both worlds! > which is a waste of movement compared to modern text editor. > Compared to > just clicking then typing But you can do that in vim. It is fully mouse aware and you can position the cursor, select text and more all with the mouse. > should change to a laptop, in which the distance between the > touchpad > and keyboard is really close (you could, sort of, say that the > keyboard > and the touchpad is a singular device). I do use a laptop but laptop pointers are universally awful in my experience! > I could even argue that moving the hand from the home position to > touchpad is shorter than moving the hand from home position to Esc > key, > which you have to do many times in vim. Thats a valid point, but less so in vim. The ESC key was originally easily within reach of the little finger but with the introduction of PCs it has moved further away. > text editor, you could use shift+directional[1] to select text very > quickly, you can't do that in the almighty vim, you must instead > type You can use the usual selection movements using Visual mode in vim. drag select or shift select both work as expected > "y(ank)-an_obscure_direction_that_is_slow_to_work_with But no vim power user does that. They use the navigational power of vim to jump directly to where they want to be. As i said earlier I virtually never use the number commands, I use the search features or the t/f set. Thus yt<str> or yf<str> or for long sections ,./<searchstr>/y > [1] directional isn't only up, down, left, and right, but also home, > end, page up, page down, and ctrl+directional, most people never > fully > utilize the extended directionals and instead uses the mouse (or in > case > of vim users, keyboards) more than is really necessary (instead of > balancing between keyboard and mouse usage). And all of those movements exist in vi.vim plus quite a few others as well - half page movements up down left and right movement to/from a letter or regex etc etc Its not visual and if you like visual you probably won't like vi (which is ironic since vi is short for visual! - as opposed to line oriented) > I know I can use the arrow key, but that doesn't seems to be the > preferred choice of vim-ers when they're in editing mode (now with > correct terminology) Experienced users prefer hjkl purely because its faster than stretching to the arrow keys... But beginners nearly always use the arrow keys. > (when I had the time I will surely approach them), I never thought > SQL > as a programming language, SQL is fully Turing complete. Some people write full business applications in pure SQL. its just a different way of thinking about control flow etc. Its more akin to prolog than Python. > redundant and is pale compared to modern text-editor that do > acknowledge > mouse as a primary input device. vim does use the mouse as a primary device. I'm confused at the comments re vim but I totally understand them in the context of vi. But back to what I said at the beginning, if you don't like vi./vim there are lots of other choices and just go with the one that works for you. Alan g. From steve at alchemy.com Sun Aug 17 00:17:09 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 16 Aug 2008 15:17:09 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <g87hkv$n84$1@ger.gmane.org> References: <mailman.17249.1218833940.920.tutor@python.org> <1218902839.6352.141.camel@lieryan-laptop> <g87hkv$n84$1@ger.gmane.org> Message-ID: <48A751E5.90504@alchemy.com> As a meta-comment on this discussion (hopefully to avoid fueling the editor holy war further), there's a reason sophisticated editors such as vi[m] and EMACS (and a dozen others I could name) exist and remain popular so long after they were introduced (which may well have been longer ago than some on this list have been alive). They tend to be very, very, very good at doing certain things with text. Complaints about not liking the style of the interface or standard keybindings are understandable, but generally with these sophisticated tools, it's possible to completely redefine all of those elements to suit your personal style anyway. However, in my experience, complaints about these editors lacking capability or being too awkward to really use effectively generally stem from a lack of experience or in-depth knowledge of how to use those tools. I've heard many people say how they can't believe people would struggle through using vi when it's so fast and easy to use a mouse and easy-to-remember keys and menus, and how much faster they can perform their editing operations that way. And many times when I've worked with them on something and fired up vi and started flying all over the document changing things, or using the more powerful commands to make transformations over the whole text with a few keystrokes, I've heard "I... didn't know you could DO that!" (and I know people who know vi much, much better than I do). Like any complex tool, the time you invest in learning how to *really* harness its power will pay off. Likewise, there's a reason the IDE environments like Visual Studio or Eclipse, and pointy-clicky-WYSIWYG editing tools exist. They're much easier for beginners to learn, not as intimidating, but in the end they don't pay off with anywhere close to the amount of text-document-altering power. Their payoff is in another arena... things like having an IDE write giant chunks of boilerplate code for you, or making it easy for people whose editing needs are just to tweak a few lines here and there in an existing document (like an auto-generated template from the IDE). They're just tools. Pick the ones that work for the jobs you need to get done, but don't assume that the other ones are pointless. They may either have points you don't need, or you may not have realized their importance yet. --steve From steve at alchemy.com Sun Aug 17 00:25:57 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 16 Aug 2008 15:25:57 -0700 Subject: [Tutor] What has Editor X got that PyWin32 hasn't? In-Reply-To: <48A751E5.90504@alchemy.com> References: <mailman.17249.1218833940.920.tutor@python.org> <1218902839.6352.141.camel@lieryan-laptop> <g87hkv$n84$1@ger.gmane.org> <48A751E5.90504@alchemy.com> Message-ID: <48A753F5.1050306@alchemy.com> Steve Willoughby wrote: > Likewise, there's a reason the IDE environments like Visual Studio or > Eclipse, and pointy-clicky-WYSIWYG editing tools exist. They're much > easier for beginners to learn, not as intimidating, but in the end they For example, I use pyWin or IDLE all the time if I want to play interactively with the interpreter or demonstrate a really simple thing. If I go to write a 10,000-line or 50,000-line application you can bet money it will be with vim or emacs (or maybe eclipse but usually not even that). On the other hand, I'm teaching some people in my family how to program computers, and for the time being they have enough to learn just mastering the basics. They're using IDLE and pyWin. Those are easy, obvious how to do what they need to do, and can focus on learning Python itself without remembering what key does what in the editor. I love those simpler, more visual, editors for situations like that. From emadnawfal at gmail.com Sun Aug 17 01:28:42 2008 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Sat, 16 Aug 2008 19:28:42 -0400 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <20080816180923.GB23065@dragon.alchemy.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> <20080816180923.GB23065@dragon.alchemy.com> Message-ID: <652641e90808161628t5f468feaob162ff32d28e8ca2@mail.gmail.com> Thank you so much Steve, I followed your advice about calculating o the fly and it really rang a bell. Now I have this script. It's faster and does not give me the nasty memory error message the first one sometimes did: # Chi-squared collocation discovery # Important definitions first. Let's suppose that we # are trying to find whether "powerful computers" is a collocation # N = The number of all bigrams in the corpus # O11 = how many times the bigram "powerful computers" occurs in the corpus # O22 = the number of bigrams not having either word in our collocation = N - O11 # O12 = The number of bigrams whose second word is our second word # but whose first word is not "powerful" # O21 = The number of bigrams whose first word is our first word, but whose second word # is different from oour second word ########################################################### print """ ************************************************* * Welcome to the Collocationer * * * * ************************************************* """ # Let's first get the text and turn into bigrams #tested_collocate = raw_input("Enter the bigram you think is a collocation\n") #word1 = tested_collocate.split()[0] #word2 = tested_collocate.split()[1] word1 = 'United' word2 = 'States' infile = file("1.txt") # initilize the counters N = 0 O11= 0 O22 = 0 O12 = 0 O21 = 0 for line in infile: length = len(line.split()) # a variable to hold the length of each line if len(line.split()) <=1: continue for word in line.split(): N+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 == v and word2 == line.split()[i+1]: O11 +=1 for i,v in enumerate(line.split()): if i < length -1: if word1 != v and word2 != line.split()[i+1]: O22+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 != v and word2 == line.split()[i+1]: O12+=1 for i,v in enumerate(line.split()): if i< length-1: if word1 == v and word2 != line.split()[i+1]: O21+=1 chi2 = (N * ((O11 * O22 - O12 * O21) ** 2))/ float((O11 + O12) * (O11 + O21) * (O12 + O22) * (O21 + O22)) print "Chi-Squared = ", chi2 if chi2 > 3.841: print "These two words form a collocation" else: print "These two words do not form a collocation" On Sat, Aug 16, 2008 at 2:09 PM, Steve Willoughby <steve at alchemy.com> wrote: > On Sat, Aug 16, 2008 at 01:55:36PM -0400, Emad Nawfal (???? ????) wrote: > > Hello Tutors, > > I'm trying to write a small scrip to find collocations using chi squared, > > Minor nit, but the word you're looking for here is "script". "Scrip" > is also an English word but means something completely different. > Looking professional in a field includes using the jargon correctly. > > > depending on a fairly big corpus. > > The program below does a good job, but it's too slow, and I need to > process > > something like 50 million words. > > How can I make it run fast? > > How fast is fast enough? > What's its time now? > Can you identify where it might be slowing down? > > Depending on the order of magnitude of the speedup you're looking > to achieve, the answer could be very different. > > > # Let's first get the text and turn into bigrams > > bigrams = [] > > infile = file("corpus.txt") > > text = infile.read().lower().split() > > This strikes me as needlessly memory-consuming. You might want to > iterate over lines of text instead of sucking the entire file into > a giant string. I'm guessing you want to recognize words next to > one another even if separated by a newline? Be aware of the cost, > though, of passing potentially huge data values around. > > > infile.close() > > for i,v in enumerate(text): # get words and their ranking number > > if i < len(text)-1: # This guarntees that the list index is not out > of > > range > > bigram = v, text[i+1] # each word and the two succeding words > > bigrams.append(bigram) > > Why don't you trust enumerate's i values, out of curiosity? > > It seems to me if you think of what you're collecting here > you could do some calculating on the fly as you look through > the list of words and wouldn't need to be building these > lists and then going back through them. > > I'm trying to give some vague help without doing the work for you > because we don't do homework exercises for people :) > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/7ec47565/attachment.htm> From kent37 at tds.net Sun Aug 17 02:11:22 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Aug 2008 20:11:22 -0400 Subject: [Tutor] Beginner problem: name 'convertToFahrenheit' is not defined In-Reply-To: <1218906973.6352.198.camel@lieryan-laptop> References: <mailman.17424.1218865216.920.tutor@python.org> <1218887435.6352.82.camel@lieryan-laptop> <aac792e80808160907l5ad5e739h695a3665b15a07e@mail.gmail.com> <1218906973.6352.198.camel@lieryan-laptop> Message-ID: <1c2a2c590808161711y28001db9p8b22ea7560f413d8@mail.gmail.com> On 8/16/08, Lie Ryan <lie.1296 at gmail.com> wrote: > never use input(), use raw_input() instead. input() parses the string it > receives first, and may (read: WILL in the hands of certain persons) > allow user to input certain strings that get parsed into dangerous > codes. Use int(raw_input()) instead to convert the result of raw_input > (i.e. string) into a number (i.e. integer). Probably float(raw_input()) would be better in this program. Kent From david at abbottdavid.com Sun Aug 17 02:58:28 2008 From: david at abbottdavid.com (David) Date: Sat, 16 Aug 2008 20:58:28 -0400 Subject: [Tutor] MySQLdb simple menu Message-ID: <48A777B4.4030406@abbottdavid.com> New to python and programming. This works but I don't like the way it is set up. I would like to have a simple menu like; [code] def options(): print \ """ Options: 'p' Print Options 'l' Login 'c' Create account 'q' Quit """ options() def choice(): choice = "p" while choice != "q": choice = raw_input("Options: ") if choice == "p": print options() if choice == "l": login() if choice == "c": newlogin() if choice == "q": sys.exit(0) else: print "That option does not exsist!" choice = raw_input("Option: ") choice() [/code] But I can't get it to work, I can't get past; [code] for row in rows: [/code] Works but I don't like that you have to try to login first, would like it to give you the option to; login create account print menu exit [code] import sys import MySQLdb import MySQLdb.cursors conn = MySQLdb.Connect( host='localhost', user='root', passwd='atlantic', db='python', compress=1, cursorclass=MySQLdb.cursors.DictCursor) cursor = conn.cursor() cursor.execute("SELECT * FROM login") rows = cursor.fetchall() cursor.close() conn.close() username = raw_input("Enter your username (q to exit): ") password = raw_input("Enter your password (q to exit): ") for row in rows: if username == row['username'] and password == row['password']: print "Hello", username sys.exit(0) else: r = raw_input("Login failed, do you want to create an account? [y/n]") if r != 'y' : sys.exit(0) newname = "" data = [] newname = raw_input("Please enter a username: ") newpw = raw_input("Please enter a password: ") tuple = (newname, newpw) data.append(tuple) db = MySQLdb.connect( host="localhost", user="root", passwd="atlantic", db="python") cursor = db.cursor() cursor.executemany( "INSERT INTO login (username, password)VALUES (%s, %s)", data) [/code] -- Have Fun, David A. Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From bgailer at gmail.com Sun Aug 17 04:28:42 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 16 Aug 2008 22:28:42 -0400 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <652641e90808161628t5f468feaob162ff32d28e8ca2@mail.gmail.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> <20080816180923.GB23065@dragon.alchemy.com> <652641e90808161628t5f468feaob162ff32d28e8ca2@mail.gmail.com> Message-ID: <48A78CDA.8080602@gmail.com> Emad Nawfal (???? ????) wrote: > Thank you so much Steve, > I followed your advice about calculating o the fly and it really rang > a bell. Now I have this script. It's faster and does not give me the > nasty memory error message the first one sometimes did: > # Chi-squared collocation discovery > # Important definitions first. Let's suppose that we > # are trying to find whether "powerful computers" is a collocation > # N = The number of all bigrams in the corpus > # O11 = how many times the bigram "powerful computers" occurs in the > corpus > # O22 = the number of bigrams not having either word in our > collocation = N - O11 > # O12 = The number of bigrams whose second word is our second word > # but whose first word is not "powerful" > # O21 = The number of bigrams whose first word is our first word, but > whose second word > # is different from oour second word > ########################################################### > > print """ > ************************************************* > * Welcome to the Collocationer > * * > * * > ************************************************* > """ > # Let's first get the text and turn into bigrams > #tested_collocate = raw_input("Enter the bigram you think is a > collocation\n") > #word1 = tested_collocate.split()[0] > #word2 = tested_collocate.split()[1] > word1 = 'United' > word2 = 'States' > > infile = file("1.txt") > # initilize the counters > > N = 0 > O11= 0 > O22 = 0 > O12 = 0 > O21 = 0 > for line in infile: > length = len(line.split()) # a variable to hold the length of each > line > > if len(line.split()) <=1: > continue > for word in line.split(): > N+=1 > for i,v in enumerate(line.split()): > if i< length-1: > if word1 == v and word2 == line.split()[i+1]: > O11 +=1 > for i,v in enumerate(line.split()): > if i < length -1: > if word1 != v and word2 != line.split()[i+1]: > O22+=1 > for i,v in enumerate(line.split()): > if i< length-1: > if word1 != v and word2 == line.split()[i+1]: > O12+=1 > for i,v in enumerate(line.split()): > if i< length-1: > if word1 == v and word2 != line.split()[i+1]: > O21+=1 > > > > > chi2 = (N * ((O11 * O22 - O12 * O21) ** 2))/ float((O11 + O12) * (O11 > + O21) * (O12 + O22) * (O21 + O22)) > print "Chi-Squared = ", chi2 > if chi2 > 3.841: > print "These two words form a collocation" > else: > print "These two words do not form a collocation" > I'd like to jump in here and offer a few refinements that make the code simpler and more "Pythonic". In the background I'm also researching how to use dictionaries to make things even better. Some guidelines: - use initial lower case for variable and function names, upper case for classes - don't repeat calculations - do them once and save the result in a variable - don't repeat loops - you can put the calculations for o11 o12 o21 and o22 all under 1 for loop - obtain one word at a time as rightWord and then save it as leftWord # your initial code goes here, up to but not including # for line in infile: line = infile.readline().split() # get the first line so we can get the first word leftWord = line[0] line = line[1:] # drop the first word n = 1 # count the first word o11 = o12 = o21 = o22 = 0 while line: n += len(line) # count words for rightWord in line: if word1 == leftWord and word2 == rightWord: o11 += 1 elif word1 != leftWord and word2 != rightWord: o22 += 1 elif word1 != leftWord and word2 == rightWord: o12 += 1 else: # no need to test o21 += 1 leftWord = rightWord line = infile.readline().split() # rest of your code follows starting with # chi2 = ... # If you want to get even "sexier" you could create an array of counters # counters = [[0,0],[0,0]] # where the elements left to right represent o22, o12, o21 and o11 # taking advantage of the fact that False == 0 and True == 1: for rightWord in line: counters[word1 == leftWord][word2 == rightWord] += 1 leftWord = rightWord line = infile.readline().split() -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From bgailer at gmail.com Sun Aug 17 04:33:41 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 16 Aug 2008 22:33:41 -0400 Subject: [Tutor] For Loops and nested loops In-Reply-To: <BAY117-W53F931F120AA1620AD3C16826C0@phx.gbl> References: <BAY117-W2038EBB1B32FC8CD7FD730826C0@phx.gbl> <48A6E3C5.1090800@gmail.com> <BAY117-W53F931F120AA1620AD3C16826C0@phx.gbl> Message-ID: <48A78E05.9020501@gmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080816/f663f8fe/attachment.htm> From david at abbottdavid.com Sun Aug 17 04:48:54 2008 From: david at abbottdavid.com (David) Date: Sat, 16 Aug 2008 22:48:54 -0400 Subject: [Tutor] MySQLdb simple menu In-Reply-To: <48A777B4.4030406@abbottdavid.com> References: <48A777B4.4030406@abbottdavid.com> Message-ID: <48A79196.7030400@abbottdavid.com> David wrote: > New to python and programming. This works but I don't like the way it > is set up. I would like to have a simple menu like; > [code] > def options(): > print \ > """ Options: > 'p' Print Options > 'l' Login > 'c' Create account > 'q' Quit > """ > > options() > > def choice(): > choice = "p" > while choice != "q": > choice = raw_input("Options: ") > if choice == "p": > print options() > > if choice == "l": > login() > > if choice == "c": > newlogin() > > if choice == "q": > sys.exit(0) > > else: > print "That option does not exsist!" > choice = raw_input("Option: ") > choice() > [/code] > > But I can't get it to work, I can't get past; > [code] > for row in rows: > [/code] > > > Works but I don't like that you have to try to login first, would like > it to give you the option to; > > login > create account > print menu > exit > > [code] > import sys > import MySQLdb > import MySQLdb.cursors > > conn = MySQLdb.Connect( > host='localhost', user='root', > passwd='atlantic', db='python', compress=1, > cursorclass=MySQLdb.cursors.DictCursor) > > cursor = conn.cursor() > cursor.execute("SELECT * FROM login") > rows = cursor.fetchall() > cursor.close() > conn.close() > username = raw_input("Enter your username (q to exit): ") > password = raw_input("Enter your password (q to exit): ") > > for row in rows: > > if username == row['username'] and password == row['password']: > print "Hello", username > sys.exit(0) > > else: > r = raw_input("Login failed, do you want to create an account? [y/n]") > if r != 'y' : sys.exit(0) > > newname = "" > data = [] > newname = raw_input("Please enter a username: ") > newpw = raw_input("Please enter a password: ") > tuple = (newname, newpw) > data.append(tuple) > db = MySQLdb.connect( > host="localhost", > user="root", > passwd="atlantic", > db="python") > cursor = db.cursor() > > cursor.executemany( > "INSERT INTO login (username, password)VALUES (%s, %s)", data) > [/code] > How does this look; #!/usr/bin/python #Filename : choices.py import sys import MySQLdb import MySQLdb.cursors def login(): conn = MySQLdb.Connect( host='localhost', user='root', passwd='atlantic', db='python', compress=1, cursorclass=MySQLdb.cursors.DictCursor) cursor = conn.cursor() cursor.execute("SELECT * FROM login") rows = cursor.fetchall() cursor.close() conn.close() username = raw_input("Enter your username (q to exit): ") password = raw_input("Enter your password (q to exit): ") for row in rows: if username == row['username'] and password == row['password']: print "Hello", username sys.exit(0) print "Login failed!" def newlogin(): newname = "" data = [] newname = raw_input("Please enter a username: ") newpw = raw_input("Please enter a password: ") tuple = (newname, newpw) data.append(tuple) db = MySQLdb.connect( host="localhost", user="root", passwd="atlantic", db="python") cursor = db.cursor() cursor.executemany( "INSERT INTO login (username, password)VALUES (%s, %s)", data) print "Account created for", newname sys.exit(0) def options(): print \ """ Please pick one: 'p' Print Options 'l' Login 'c' Create account 'q' Quit """ options() choice = "p" while choice != "q": choice = raw_input("Please pick an option: ") if choice == "p": options() elif choice == "l": login() elif choice == "c": newlogin() elif choice == "q": print "Goodbye!" seems to work OK. -- Have Fun, David A. Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From xboxmuncher at gmail.com Sun Aug 17 07:28:23 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 17 Aug 2008 01:28:23 -0400 Subject: [Tutor] Is there python editor or plugin for a python editor for curly brackets around code blocks? In-Reply-To: <e775286d0808132216k2cac191n15ba55acdbaadc3c@mail.gmail.com> References: <df531c470808122145i61d2fabdlaf65ea5008a2142f@mail.gmail.com> <200808130323.28861.cfuller084@thinkingplanet.net> <df531c470808132006m529832e0g9c11a8745c2a6745@mail.gmail.com> <584940990808132039p5856de7nf8d66749b2c3d656@mail.gmail.com> <df531c470808132108n74f28a06u5088bde6378c5e16@mail.gmail.com> <e775286d0808132216k2cac191n15ba55acdbaadc3c@mail.gmail.com> Message-ID: <df531c470808162228y25eeb915j286ac0933d36e08d@mail.gmail.com> I talked about earlier how the main problem for me wanting to use curly braces is because of the visual ease of seeing the end of the code blocks.. well you can change the indention guidelines on most code editors to a bright color and this might be the next best thing. Also a good feature to implement is just like there are highlighted curly braces when your mouse or key presses are inside certain code blocks, they should highlight or change the indentation guides to the same effect.... On Thu, Aug 14, 2008 at 1:16 AM, Timothy Grant <timothy.grant at gmail.com>wrote: > On Wed, Aug 13, 2008 at 9:08 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > > I don't see what the big deal is on coming up with the .{ #{, and other > > bracket types to try to not interfere with normal bracket use in python. > Its > > relatively easy to create a parser to identify the brackets in use > normally > > and the code block brackets, with regex or without. > > > > On Wed, Aug 13, 2008 at 11:39 PM, Chad Crabtree <flaxeater at gmail.com> > wrote: > >> > >> Oh, I forgot there's another way to add braces > >> > >> if it_is_way_cool: #{ > >> print 'coolness' > >> #} > >> > >> On Wed, Aug 13, 2008 at 11:06 PM, xbmuncher <xboxmuncher at gmail.com> > wrote: > >> > I'll check out your links. But in response to some of the things said: > >> > I'm a fan of indentation, a replacement of indentation with curly > braces > >> > is > >> > not what I was aiming for. If I could have it my way, I'd have > >> > indentation > >> > and curly braces. I don't want to change official python syntax > either.. > >> > I > >> > just want to be able to easily do it myself. > >> > > >> > The big problem I had that I didn't explain well enough when I said > >> > "visually" is that it is visually hard to tell when code blocks end > when > >> > other code blocks and statements begin immediately after them. With > >> > curly > >> > braces you can easily visualize when looking at a lot of code where > the > >> > code > >> > block ends. The best thing you can do in python currently is to put an > >> > empty > >> > line in between the last line of a code block and the following code, > so > >> > you > >> > can better visualize the end of the code block. > >> > > >> > On Wed, Aug 13, 2008 at 4:23 AM, Chris Fuller > >> > <cfuller084 at thinkingplanet.net> wrote: > >> >> > >> >> Some clarifications w.r.t. indentation and Python: > >> >> http://www.secnetix.de/olli/Python/block_indentation.hawk > >> >> > >> >> It's just a joke, really: > >> >> http://timhatch.com/projects/pybraces/ > >> >> > >> >> Turnabout is fair play! > >> >> http://blog.micropledge.com/2007/09/nobraces/ > >> >> > >> >> Also, pindent.py in the Tools/scripts directory of your Python > >> >> distribution > >> >> will produce correctly indented scripts if the blocks are designated > >> >> with > >> >> a "#end" line. > >> >> > >> >> > >> >> But seriously, you don't want to go creating a separate class of > source > >> >> file. > >> >> It'll be harder for you and the other programmers to context switch > >> >> when > >> >> working with code that uses the standard style, will confuse others > who > >> >> won't > >> >> know what to do with your code, adds overhead to the compiling, will > >> >> break > >> >> when somebody tries to run it under the standard environment, could > >> >> clutter > >> >> up your development directories, depending on the implementation, > etc. > >> >> > >> >> Here's a thread from 1999 on the Python mailing list that discusses > the > >> >> issue: > >> >> http://mail.python.org/pipermail/python-list/1999-June/004450.html > >> >> > >> >> There's another script towards the end that might even do what you > >> >> want, > >> >> but > >> >> you might want to read what they have to say first :) > >> >> > >> >> Cheers > >> >> _______________________________________________ > >> >> Tutor maillist - Tutor at python.org > >> >> http://mail.python.org/mailman/listinfo/tutor > > > > If it's no big deal to parse the braces, I would encourage you to > write your own python preprocessor to handle that for you. > > > -- > Stand Fast, > tjg. [Timothy Grant] > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080817/e4575948/attachment.htm> From xboxmuncher at gmail.com Sun Aug 17 07:35:27 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Sun, 17 Aug 2008 01:35:27 -0400 Subject: [Tutor] Downloading RTSP streams quicker than real time streaming Message-ID: <df531c470808162235x276f4ad5v2e2edb1a98eb39a3@mail.gmail.com> Trying to create a program to download RTSP streams. I know that RTSP streams are live, so its hard to know if the stream will ever end, but the streams I'm concerned about are fixed length. *I wonder if its possible to know if the streaming content is fixed length or not.... * *Anyways*, I'm wanting to be able to quicken the streaming (thus download) of the stream, maybe to trick it by sending whatever signal required to make it stream more pieces of information quicker, so I can download the stream quicker than real time streaming. I've searched for a *RTSP library for python*.. haven't found anything useful, mostly unanswered threads in other mailing lists! *So do you know of one? or perhaps any other useful information/pointers/source that could help in the tasks described above?* -thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080817/7407e985/attachment.htm> From robert.johansson at math.umu.se Sun Aug 17 11:33:28 2008 From: robert.johansson at math.umu.se (Robert Johansson) Date: Sun, 17 Aug 2008 11:33:28 +0200 Subject: [Tutor] unsupported characters Message-ID: <000001c9004c$516e2fe0$f44a8fa0$@johansson@math.umu.se> Hi, I have problems using characters from the Swedish language. I tried the following in IDLE under MacOS X leopard (running Python 2.5.1) : S=??? Displaying error message: ?unsupported characters in input?. Running Python from a terminal I can?t even type the character, all that happens is that I get a little ?boing? from my machine.I tried to set various things like LC_CTYPE with the locale module but that doesn?t work. I don?t really know what that module does but If I try locale.getlocale(), I get: (?sv_SE?,?ISO8859-1?). Anyone who knows how to fix this? I would be very grateful. /Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080817/f66af4dd/attachment.htm> From kent37 at tds.net Sun Aug 17 15:15:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Aug 2008 09:15:40 -0400 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <652641e90808161628t5f468feaob162ff32d28e8ca2@mail.gmail.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> <20080816180923.GB23065@dragon.alchemy.com> <652641e90808161628t5f468feaob162ff32d28e8ca2@mail.gmail.com> Message-ID: <1c2a2c590808170615u435443dch6d05c3ae5f8a6aea@mail.gmail.com> On 8/16/08, Emad Nawfal (???? ????) <emadnawfal at gmail.com> wrote: > Thank you so much Steve, > I followed your advice about calculating o the fly and it really rang a > bell. Now I have this script. It's faster and does not give me the nasty > memory error message the first one sometimes did: A few hints: - You shoulld just split the line once and save the result - the current code splits the line several times for each word. - You could make a generator that returns pairs of words, that would simplify the loop code. - There is a difference between making the code fast for a single test, and making it fast for many tests. For a single test, the best solution is probably something like what you have, computing the numbers you need as you make a single pass through the data. For multiple tests, you will do better if you create some helper dictionaries that allow you to look up words and pairs quickly. You could use the pickle module to save the dicts and re-read them on subsequent runs. HTH - I can't flesh these out right now. Kent From lie.1296 at gmail.com Sun Aug 17 15:24:45 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 17 Aug 2008 20:24:45 +0700 Subject: [Tutor] Tutor Digest, Vol 54, Issue 63 In-Reply-To: <mailman.35.1218967214.1698.tutor@python.org> References: <mailman.35.1218967214.1698.tutor@python.org> Message-ID: <1218979485.6352.249.camel@lieryan-laptop> > Message: 3 > Date: Sun, 17 Aug 2008 01:28:23 -0400 > From: xbmuncher <xboxmuncher at gmail.com> > Subject: Re: [Tutor] Is there python editor or plugin for a python > editor for curly brackets around code blocks? > To: "Timothy Grant" <timothy.grant at gmail.com> > Cc: tutor at python.org > Message-ID: > <df531c470808162228y25eeb915j286ac0933d36e08d at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I talked about earlier how the main problem for me wanting to use > curly > braces is because of the visual ease of seeing the end of the code > blocks.. > well you can change the indention guidelines on most code editors to a > bright color and this might be the next best thing. Also a good > feature to > implement is just like there are highlighted curly braces when your > mouse or > key presses are inside certain code blocks, they should highlight or > change > the indentation guides to the same effect.... Highlighted braces are only useful for detecting misleading indentation, in python, since indentation is part of the syntax (instead of just a visual marker) highlighting brace/indentation lost 50% of its usefulness. In python, to see where a block ends, you just need to skim for the first line that have less indentation than the current block. Well, admittably, in a multilevel block that ends at the same time, it is sometimes hard to identify which level is ended, especially if the indentation is small: def blah(): def innerfunc(foo): for i in range(100): if i == foo: while i: i -= 1 for i in range(10): print i innerfunc(10) but that's why PEP 8 (Style Guidelines) recommends using 4 spaces which is quite a lot. Anyway, if you have a code that is more than 4 levels deep, it is a good indication that it may require refactoring. From rick at niof.net Sun Aug 17 17:50:41 2008 From: rick at niof.net (Rick Pasotto) Date: Sun, 17 Aug 2008 11:50:41 -0400 Subject: [Tutor] help with sorted() Message-ID: <20080817155041.GR2609@niof.net> I have a dictionary that looks like: d = {k:[v1,[v2,v3,v4]]} v1,v2,v3,v4 are integers. I want to print the dictionary sorted by v1, high to low. sorted(d,operator.itemgetter(0),reverse=True) gives me the keys in some order different than if I just looped through the dictionary and not in key order but also not in any order that I can see. It really appears random. sorted(d) does give me a sorted list of keys. How do I sort on v1? How would I sort on v3? -- "Many people think that if they were only in some other place, or had some other job, they would be happy. Well, that is doubtful. So get as much happiness out of what you are doing as you can and don't put off being happy until some future date." -- Dale Carnegie Rick Pasotto rick at niof.net http://www.niof.net From jozzy_a at hotmail.com Sun Aug 17 22:08:37 2008 From: jozzy_a at hotmail.com (optimum) Date: Sun, 17 Aug 2008 13:08:37 -0700 (PDT) Subject: [Tutor] Gaussian function Message-ID: <19022946.post@talk.nabble.com> Hey. Is there anyone who can give me some help? I am having trouble with the gaussian function and don't really know where to start. Below is the question I was set. "Write a program which asks the user for values of xmin, dx and nx. The program should then output a plot of the gaussian function at the following series of values of x: xmin, xmin+dx, xmin+2*dx, xmin+3*dx, : : :, xmin+(nx-1)*dx. e.g. the following output should result if xmin = 2:5, dx = 0:5 and nx = 11. -2.50 * -2.00 *** -1.50 ****** -1.00 ************ -0.50 ****************** 0.00 ******************** 0.50 ****************** 1.00 ************ 1.50 ****** 2.00 *** 2.50 * The program should contain and make full use of the following functions: gauss(x) - Returns the value of the Gaussian function line(n) - Prints a line of n asterisks followed by a newline character. You will need to choose a scale for your plot; in the example shown the number of asterisks is 50 * gauss(x). Should I start with a program like this? s='' for n in range (0,100): s=s+ '*' print s Thanks for any help received. :confused: -- View this message in context: http://www.nabble.com/Gaussian-function-tp19022946p19022946.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sun Aug 17 22:50:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Aug 2008 16:50:26 -0400 Subject: [Tutor] help with sorted() In-Reply-To: <20080817155041.GR2609@niof.net> References: <20080817155041.GR2609@niof.net> Message-ID: <1c2a2c590808171350l576038fcw897ba96b13d79dd3@mail.gmail.com> On 8/17/08, Rick Pasotto <rick at niof.net> wrote: > I have a dictionary that looks like: d = {k:[v1,[v2,v3,v4]]} > > v1,v2,v3,v4 are integers. > > I want to print the dictionary sorted by v1, high to low. Do you want just the keys, or the key/value pairs, or what? > sorted(d,operator.itemgetter(0),reverse=True) > > gives me the keys in some order different than if I just looped through > the dictionary and not in key order but also not in any order that I can > see. It really appears random. This will give you the keys in order by their first letter (assuming the keys are strings). > sorted(d) does give me a sorted list of keys. Assuming you want the keys sorted by v1. You have to write a function which, given a key, returns v1. That would be def getv1(key): return d[key][0] Then use this as the sort key: sorted(d, key=getv1, reverse=True) Kent From kent37 at tds.net Sun Aug 17 22:53:23 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Aug 2008 16:53:23 -0400 Subject: [Tutor] unsupported characters In-Reply-To: <1214103052798061254@unknownmsgid> References: <1214103052798061254@unknownmsgid> Message-ID: <1c2a2c590808171353x5a4d7409t105edcdf2eb06e23@mail.gmail.com> On 8/17/08, Robert Johansson <robert.johansson at math.umu.se> wrote: > Hi, I have problems using characters from the Swedish language. I tried the > following in IDLE under MacOS X leopard (running Python 2.5.1) : > S='?' > Displaying error message: "unsupported characters in input". To use non-ascii characters in Python code you have to declare the encoding of the source file with a comment such as # coding=UTF-8 See http://python.org/dev/peps/pep-0263/ Kent From kent37 at tds.net Sun Aug 17 22:57:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Aug 2008 16:57:33 -0400 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> Message-ID: <1c2a2c590808171357o4ae876f5m1bb2a68cf37945b9@mail.gmail.com> On 8/16/08, Emad Nawfal (???? ????) <emadnawfal at gmail.com> wrote: > #! usr/bin/python > # Chi-squared collocation discovery > # Important definitions first. Let's suppose that we > # are trying to find whether "powerful computers" is a collocation > # N = The number of all bigrams in the corpus > # O11 = how many times the bigram "powerful computers" occurs in the corpus > # O22 = the number of bigrams not having either word in our collocation = N > - O11 > # O12 = The number of bigrams whose second word is our second word > # but whose first word is not "powerful" This is just the number of occurrances of the second word - O11, isn't it? > # O21 = The number of bigrams whose first word is our first word, but whose > second word > # is different from oour second word This is the number of occurrances of the first word - O11. So one way to solve this would be to make two dictionaries - one which counts bigrams and one which counts words. Then you would get the numbers with just three dictionary lookups. Kent From bgailer at gmail.com Sun Aug 17 23:26:46 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 17 Aug 2008 17:26:46 -0400 Subject: [Tutor] Gaussian function In-Reply-To: <19022946.post@talk.nabble.com> References: <19022946.post@talk.nabble.com> Message-ID: <48A89796.6090300@gmail.com> optimum wrote: > Hey. Is there anyone who can give me some help? > Below is the question I was set. > This sounds like a homework assignment. We don't write programs for assignments. We offer help after you give it your best effort. > I am having trouble with the gaussian function and don't really know where > to start. > It sounds like you are having trouble with programming, not with the gaussian function. Did you run the following code? Did it give you any useful results? (I expect it to raise an exception.) At least run it and see what happens. How does it contribute to the overall result? s='' for n in range (0,100): s=s+ '*' print s Can you at least outline the program or algorithm as a starting place. > "Write a program which asks the user for values > of xmin, dx and nx. The program should then > output a plot of the gaussian function > > > at the following series of values of x: > xmin, xmin+dx, xmin+2*dx, xmin+3*dx, : : :, > xmin+(nx-1)*dx. e.g. the following output > should result if xmin = 2:5, dx = 0:5 and > nx = 11. > -2.50 * > -2.00 *** > -1.50 ****** > -1.00 ************ > -0.50 ****************** > 0.00 ******************** > 0.50 ****************** > 1.00 ************ > 1.50 ****** > 2.00 *** > 2.50 * > The program should contain and make full use > of the following functions: > gauss(x) - Returns the value of the Gaussian > function > > line(n) - Prints a line of n asterisks followed > by a newline character. > > You will need to choose a scale for your plot; > in the example shown the number of asterisks > is 50 * gauss(x). > > Should I start with a program like this? > > s='' > for n in range (0,100): > s=s+ '*' > print s > > Thanks for any help received. :confused: > -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From emadnawfal at gmail.com Mon Aug 18 02:47:21 2008 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Sun, 17 Aug 2008 20:47:21 -0400 Subject: [Tutor] simple python scrip for collocation discovery In-Reply-To: <1c2a2c590808171357o4ae876f5m1bb2a68cf37945b9@mail.gmail.com> References: <652641e90808161055o75a27545r3baff4170adb9618@mail.gmail.com> <1c2a2c590808171357o4ae876f5m1bb2a68cf37945b9@mail.gmail.com> Message-ID: <652641e90808171747i34ca8ebo9a68b873a1b1bfd6@mail.gmail.com> Hello Kent, Bob, Steve Thank you all for your help and suggestions. I believe I 'll have a good program soon. 2008/8/17 Kent Johnson <kent37 at tds.net> > On 8/16/08, Emad Nawfal (???? ????) <emadnawfal at gmail.com> wrote: > > #! usr/bin/python > > # Chi-squared collocation discovery > > # Important definitions first. Let's suppose that we > > # are trying to find whether "powerful computers" is a collocation > > # N = The number of all bigrams in the corpus > > # O11 = how many times the bigram "powerful computers" occurs in the > corpus > > # O22 = the number of bigrams not having either word in our collocation = > N > > - O11 > > # O12 = The number of bigrams whose second word is our second word > > # but whose first word is not "powerful" > > This is just the number of occurrances of the second word - O11, isn't it? > > > # O21 = The number of bigrams whose first word is our first word, but > whose > > second word > > # is different from oour second word > > This is the number of occurrances of the first word - O11. > > So one way to solve this would be to make two dictionaries - one which > counts bigrams and one which counts words. Then you would get the > numbers with just three dictionary lookups. > > Kent > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080817/b59e0cad/attachment.htm> From ashishbitsgoa at gmail.com Mon Aug 18 11:00:08 2008 From: ashishbitsgoa at gmail.com (Ashish Sethi) Date: Mon, 18 Aug 2008 14:30:08 +0530 Subject: [Tutor] problem in converting pixel data to image file Message-ID: <edb5c69c0808180200g62b34859j7441d4587d82276b@mail.gmail.com> Hi all, I have a problem in converting the pixel data (read from a string and written to a file using fromstring command in PIL ). The file handle of this file is called buffer. Now, when I tried to open the file as an image file but it didnt work. Then I read the documentation of PIL and found this written about fromstring function "Note that this function decodes pixel data, not entire images. If you have an entire image in a string, wrap it in a *StringIO *object, and use *open *to load it." so i wrote the following code.... file = StringIO.StringIO(buffer) img = Image.open(file) img.save(file, 'JPEG') *Error:* img = Image.open(file) File "/home/rahhal/python/lib/python2.4/site-packages/PIL/Image.py", line 1745, in open raise IOError("cannot identify image file") IOError: cannot identify image file Can any one please help in solving my problem?? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/e7a1c2bd/attachment.htm> From lie.1296 at gmail.com Mon Aug 18 12:15:31 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 18 Aug 2008 17:15:31 +0700 Subject: [Tutor] Tutor Digest, Vol 54, Issue 64 In-Reply-To: <mailman.17958.1219006663.920.tutor@python.org> References: <mailman.17958.1219006663.920.tutor@python.org> Message-ID: <1219054531.6305.19.camel@lieryan-laptop> > Message: 1 > Date: Sun, 17 Aug 2008 11:33:28 +0200 > From: "Robert Johansson" <robert.johansson at math.umu.se> > Subject: [Tutor] unsupported characters > To: <Tutor at python.org> > Message-ID: <000001c9004c$516e2fe0$f44a8fa0$@johansson at math.umu.se> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, I have problems using characters from the Swedish language. I > tried the > following in IDLE under MacOS X leopard (running Python 2.5.1) : > > > > S=??? > > > > Displaying error message: ?unsupported characters in input?. > This is because Python 2, by default, assumed ASCII encoding for its source codes (Python 3, by default, assumed utf-8, I think). You can change the default encoding by adding this "magic comment": # coding=<encoding name> or: # -*- coding: <encoding name> -*- or: # vim: set fileencoding=<encoding name> : to the first or second line of your source code (usually the <encoding name> would be utf-8, but it can be any encoding supported by python). The encoding declaration may be in the first or second line to allow its usage together with pound-bang comment. read: http://www.python.org/dev/peps/pep-0263/ > > Running Python from a terminal I can?t even type the character, all > that > happens is that I get a little ?boing? from my machine.I tried to set > various things like LC_CTYPE with the locale module but that doesn?t > work. > I don?t really know what that module does but If I try > locale.getlocale(), I > get: (?sv_SE?,?ISO8859-1?). Anyone who knows how to fix this? I would > be > very grateful. > > > > /Robert > > > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > <http://mail.python.org/pipermail/tutor/attachments/20080817/f66af4dd/attachment-0001.htm> > From lie.1296 at gmail.com Mon Aug 18 12:18:27 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 18 Aug 2008 17:18:27 +0700 Subject: [Tutor] unsupported characters In-Reply-To: <1219054531.6305.19.camel@lieryan-laptop> References: <mailman.17958.1219006663.920.tutor@python.org> <1219054531.6305.19.camel@lieryan-laptop> Message-ID: <1219054707.6305.21.camel@lieryan-laptop> On Mon, 2008-08-18 at 17:15 +0700, Lie Ryan wrote: > > Message: 1 > > Date: Sun, 17 Aug 2008 11:33:28 +0200 > > From: "Robert Johansson" <robert.johansson at math.umu.se> > > Subject: [Tutor] unsupported characters > > To: <Tutor at python.org> > > Message-ID: <000001c9004c$516e2fe0$f44a8fa0$@johansson at math.umu.se> > > Content-Type: text/plain; charset="iso-8859-1" > > > > Hi, I have problems using characters from the Swedish language. I > > tried the > > following in IDLE under MacOS X leopard (running Python 2.5.1) : > > > > > > > > S=??? > > > > > > > > Displaying error message: ?unsupported characters in input?. > > > > This is because Python 2, by default, assumed ASCII encoding for its > source codes (Python 3, by default, assumed utf-8, I think). You can > change the default encoding by adding this "magic comment": > > # coding=<encoding name> > > or: > > # -*- coding: <encoding name> -*- > > or: > > # vim: set fileencoding=<encoding name> : > > to the first or second line of your source code (usually the <encoding > name> would be utf-8, but it can be any encoding supported by python). > The encoding declaration may be in the first or second line to allow its > usage together with pound-bang comment. > > read: http://www.python.org/dev/peps/pep-0263/ > > > > > Running Python from a terminal I can?t even type the character, all > > that > > happens is that I get a little ?boing? from my machine.I tried to set > > various things like LC_CTYPE with the locale module but that doesn?t > > work. > > I don?t really know what that module does but If I try > > locale.getlocale(), I > > get: (?sv_SE?,?ISO8859-1?). Anyone who knows how to fix this? I would > > be > > very grateful. > > > > > > > > /Robert > > > > > > > > > > > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > <http://mail.python.org/pipermail/tutor/attachments/20080817/f66af4dd/attachment-0001.htm> > > From kent37 at tds.net Mon Aug 18 12:29:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Aug 2008 06:29:35 -0400 Subject: [Tutor] problem in converting pixel data to image file In-Reply-To: <edb5c69c0808180200g62b34859j7441d4587d82276b@mail.gmail.com> References: <edb5c69c0808180200g62b34859j7441d4587d82276b@mail.gmail.com> Message-ID: <1c2a2c590808180329l33726a00w10443b6cc7da14b9@mail.gmail.com> On 8/18/08, Ashish Sethi <ashishbitsgoa at gmail.com> wrote: > Hi all, > I have a problem in converting the pixel data (read from a string and > written to a file using fromstring command in PIL ). > The file handle of this file is called buffer. Now, when I tried to open the > file as an image file but it didnt work. I'm confused. Why don't you use Image.save() to write the image and Image.open() to read it? Kent From lie.1296 at gmail.com Mon Aug 18 12:41:00 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 18 Aug 2008 17:41:00 +0700 Subject: [Tutor] problem in converting pixel data to image file In-Reply-To: <mailman.31.1219053621.5779.tutor@python.org> References: <mailman.31.1219053621.5779.tutor@python.org> Message-ID: <1219056060.6305.41.camel@lieryan-laptop> > Message: 3 > Date: Mon, 18 Aug 2008 14:30:08 +0530 > From: "Ashish Sethi" <ashishbitsgoa at gmail.com> > Subject: [Tutor] problem in converting pixel data to image file > To: tutor at python.org > Message-ID: > <edb5c69c0808180200g62b34859j7441d4587d82276b at mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > Hi all, > I have a problem in converting the pixel data (read from a string and > written to a file using fromstring command in PIL ). > The file handle of this file is called buffer. Now, when I tried to > open the > file as an image file but it didnt work. What is the format of the image you want to open? PIL doesn't support all image format in the world (of course), but the most common ones are supported. fromstring, by default, assumes that the string you're passing it is in raw format (i.e. the definition of raw format is explained PIL's documentation) > Then I read the documentation of PIL and found this written about > fromstring > function > "Note that this function decodes pixel data, not entire images. If you > have an entire image in a string, wrap it in a *StringIO *object, and > use > *open *to load it." StringIO is simply a wrapper around string to make it have a file-like interface (since Python uses Duck Typing principle, if an object has the same members a file-object have, like read(), write(), readlines(), etc python should not differentiate them) > so i wrote the following code.... > > file = StringIO.StringIO(buffer) > img = Image.open(file) > img.save(file, 'JPEG') > > *Error:* > img = Image.open(file) > File "/home/rahhal/python/lib/python2.4/site-packages/PIL/Image.py", > line > 1745, in open > raise IOError("cannot identify image file") > IOError: cannot identify image file PIL is it cannot identify what format the original image is in, either you pass explicitly what format the original file is in, or (at the worst case) you create (or search whether one is available on the internet) your own decoder. PS: List of image format supported by PIL (you can also find it in PIL's documentation): BMP BUFR (identify only) CUR (read only) DCX (read only) EPS (write-only) FITS (identify only) FLI, FLC (read only) FPX (read only) GBR (read only) GD (read only) GIF GRIB (identify only) HDF5 (identify only) ICO (read only) IM IMT (read only) IPTC/NAA (read only) JPEG MCIDAS (read only) MIC (read only) MPEG (identify only) MSP PALM (write only) PCD (read only) PCX PDF (write only) PIXAR (read only) PNG PPM PSD (read only) SGI (read only) SPIDER TGA (read only) TIFF WAL (read only) WMF (identify only) XBM XPM (read only) XV Thumbnails > Can any one please help in solving my problem?? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > <http://mail.python.org/pipermail/tutor/attachments/20080818/e7a1c2bd/attachment-0001.htm> > > ------------------------------ From lie.1296 at gmail.com Mon Aug 18 15:02:30 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 18 Aug 2008 20:02:30 +0700 Subject: [Tutor] problem in converting pixel data to image file In-Reply-To: <edb5c69c0808180354w2c188a6dl2a9acfc2c734f5ed@mail.gmail.com> References: <mailman.31.1219053621.5779.tutor@python.org> <1219056060.6305.41.camel@lieryan-laptop> <edb5c69c0808180354w2c188a6dl2a9acfc2c734f5ed@mail.gmail.com> Message-ID: <1219064550.6305.65.camel@lieryan-laptop> On Mon, 2008-08-18 at 16:24 +0530, Ashish Sethi wrote: > Hey Lie, > Thanks for replying so promptly. > Here is my real problem which I posted as a new post:- You should always Reply-to-all so everybody in the tutor-list could see the response. > I have a problem in converting between different RGB color spaces.I > have a jpeg file in rgb mode. > The rgb data by default is in RGB[8:8:8] mode...i.e, 8 bits(1 byte) > per band(r,g,b). > I need to convert it into RGB[4:4:4] format by getting the rgb > information of each pixel in the image > and converting the ascii values obtained for the R,G and B bands into > binary form and then clip the least significant 4 bits > from this binary no. to form a 4 bit binary value and then convert > this back to ascii and and save the new information back > to the image file. Untill now, I have been able obtain the pixel > information of my image file using : > > >>> im = Image.open("image.jpg") > > >>> pix = im.load() > > >>> pix[0, 0] > > (226, 162, 125) > > 1.Now, how do i convert this ascii data to binary? You mean you want to convert the string 'A' to its binary value 65? Use the built-in function ord('A'). But the problem you seems to be having, I think, isn't about that. pix[0, 0] returns a tuple that contains the three integers for each RGB. So you just need to do something like this (sort of): for r, g, b in pix: # do something with r, g ,b > 2.how do i mask last 4 bits ( least significant bits )? I think some it, bit-wise operation would do: http://docs.python.org/ref/bitwise.html How to bit-mask: http://en.wikipedia.org/wiki/Mask_(computing) >>> v1 = int('01000101', 2) >>> v2 = int('11110000', 2) >>> print v1, v2 69 240 >>> # 69 (base-10) is 01000101 (base-2) >>> # 240 (base-10) is 11110000 (base-2) >>> print v1 & v2 # bit-wise and 65 >>> # 65 (base-10) is 01000000 (base-2) >>> # 01000101 bitwise-and 11110000 is 01000000 > 3.also, I need to convert the same image to RGB[12:12:12] mode,for > which i need to zero pad with 4 zeroes the > binary RGB[8:8:8] data. How do I do this? > So, regarding my initial problem...once i solve this problem...i will > have the pixel wise data in > an array or list...so to write this data back to the image file...i > have to use fromarray command I'm not aware that PIL has a fromarray command, do you mean fromstring? > .But that unfortunately isnt giving back an image file... I think JPEG (at least PIL's JPEG) doesn't support 4-bit/color and 12-bit/color representation. JPEG supports 'L'uminance (8-bit/pixel), RGB (8-bit/color), CMYK (I'm not sure). You probably need another image format, one that support 12-bit/color format (I'm not aware if any popular image format supports that, but I'm not imaging expert) > I would also appreciate any help you could offer me regarding the new > problem. > > Looking forward to your reply > > > > > > On 8/18/08, Lie Ryan <lie.1296 at gmail.com> wrote: > > Message: 3 > > Date: Mon, 18 Aug 2008 14:30:08 +0530 > > From: "Ashish Sethi" <ashishbitsgoa at gmail.com> > > Subject: [Tutor] problem in converting pixel data to image > file > > To: tutor at python.org > > Message-ID: > > > <edb5c69c0808180200g62b34859j7441d4587d82276b at mail.gmail.com> > > Content-Type: text/plain; charset="utf-8" > > > > Hi all, > > I have a problem in converting the pixel data (read from a > string and > > written to a file using fromstring command in PIL ). > > The file handle of this file is called buffer. Now, when I > tried to > > open the > > file as an image file but it didnt work. > > What is the format of the image you want to open? PIL doesn't > support > all image format in the world (of course), but the most common > ones are > supported. fromstring, by default, assumes that the string > you're > passing it is in raw format (i.e. the definition of raw format > is > explained PIL's documentation) > > > Then I read the documentation of PIL and found this written > about > > fromstring > > function > > "Note that this function decodes pixel data, not entire > images. If you > > have an entire image in a string, wrap it in a *StringIO > *object, and > > use > > *open *to load it." > > StringIO is simply a wrapper around string to make it have a > file-like > interface (since Python uses Duck Typing principle, if an > object has the > same members a file-object have, like read(), write(), > readlines(), etc > python should not differentiate them) > > > so i wrote the following code.... > > > > file = StringIO.StringIO(buffer) > > img = Image.open(file) > > img.save(file, 'JPEG') > > > > *Error:* > > img = Image.open(file) > > File > "/home/rahhal/python/lib/python2.4/site-packages/PIL/Image.py", > > line > > 1745, in open > > raise IOError("cannot identify image file") > > IOError: cannot identify image file > > PIL is it cannot identify what format the original image is > in, either > you pass explicitly what format the original file is in, or > (at the > worst case) you create (or search whether one is available on > the > internet) your own decoder. > > PS: List of image format supported by PIL (you can also find > it in PIL's > documentation): > BMP > BUFR (identify only) > CUR (read only) > DCX (read only) > EPS (write-only) > FITS (identify only) > FLI, FLC (read only) > FPX (read only) > GBR (read only) > GD (read only) > GIF > GRIB (identify only) > HDF5 (identify only) > ICO (read only) > IM > IMT (read only) > IPTC/NAA (read only) > JPEG > MCIDAS (read only) > MIC (read only) > MPEG (identify only) > MSP > PALM (write only) > PCD (read only) > PCX > PDF (write only) > PIXAR (read only) > PNG > PPM > PSD (read only) > SGI (read only) > SPIDER > TGA (read only) > TIFF > WAL (read only) > WMF (identify only) > XBM > XPM (read only) > XV Thumbnails > > > Can any one please help in solving my problem?? > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > > <http://mail.python.org/pipermail/tutor/attachments/20080818/e7a1c2bd/attachment-0001.htm> > > > > ------------------------------ > > From tomazbevec at yahoo.com Mon Aug 18 15:21:58 2008 From: tomazbevec at yahoo.com (Tomaz Bevec) Date: Mon, 18 Aug 2008 06:21:58 -0700 (PDT) Subject: [Tutor] problem in converting pixel data to image file In-Reply-To: <1219056060.6305.41.camel@lieryan-laptop> Message-ID: <256800.70470.qm@web32803.mail.mud.yahoo.com> Ashish, I don't know that much about image processing, but I think you should check into the Image Magick convert utility. You might be trying to re-invent the wheel. I have used Image Magick to good effect for the batch processing and conversion of images in a non-python setting. You can spawn a process from within your python code to take advantage of this program. Image Magick convert: (scroll down to see options) (http://www.imagemagick.org/script/convert.php) --Tomaz --- On Mon, 8/18/08, Lie Ryan <lie.1296 at gmail.com> wrote: > From: Lie Ryan <lie.1296 at gmail.com> > Subject: Re: [Tutor] problem in converting pixel data to image file > To: tutor at python.org > Date: Monday, August 18, 2008, 3:41 AM > > Message: 3 > > Date: Mon, 18 Aug 2008 14:30:08 +0530 > > From: "Ashish Sethi" > <ashishbitsgoa at gmail.com> > > Subject: [Tutor] problem in converting pixel data to > image file > > To: tutor at python.org > > Message-ID: > > > <edb5c69c0808180200g62b34859j7441d4587d82276b at mail.gmail.com> > > Content-Type: text/plain; charset="utf-8" > > > > Hi all, > > I have a problem in converting the pixel data (read > from a string and > > written to a file using fromstring command in PIL ). > > The file handle of this file is called buffer. Now, > when I tried to > > open the > > file as an image file but it didnt work. > > What is the format of the image you want to open? PIL > doesn't support > all image format in the world (of course), but the most > common ones are > supported. fromstring, by default, assumes that the string > you're > passing it is in raw format (i.e. the definition of raw > format is > explained PIL's documentation) > > > Then I read the documentation of PIL and found this > written about > > fromstring > > function > > "Note that this function decodes pixel data, not > entire images. If you > > have an entire image in a string, wrap it in a > *StringIO *object, and > > use > > *open *to load it." > > StringIO is simply a wrapper around string to make it have > a file-like > interface (since Python uses Duck Typing principle, if an > object has the > same members a file-object have, like read(), write(), > readlines(), etc > python should not differentiate them) > > > so i wrote the following code.... > > > > file = StringIO.StringIO(buffer) > > img = Image.open(file) > > img.save(file, 'JPEG') > > > > *Error:* > > img = Image.open(file) > > File > "/home/rahhal/python/lib/python2.4/site-packages/PIL/Image.py", > > line > > 1745, in open > > raise IOError("cannot identify image > file") > > IOError: cannot identify image file > > PIL is it cannot identify what format the original image is > in, either > you pass explicitly what format the original file is in, or > (at the > worst case) you create (or search whether one is available > on the > internet) your own decoder. > > PS: List of image format supported by PIL (you can also > find it in PIL's > documentation): > BMP > BUFR (identify only) > CUR (read only) > DCX (read only) > EPS (write-only) > FITS (identify only) > FLI, FLC (read only) > FPX (read only) > GBR (read only) > GD (read only) > GIF > GRIB (identify only) > HDF5 (identify only) > ICO (read only) > IM > IMT (read only) > IPTC/NAA (read only) > JPEG > MCIDAS (read only) > MIC (read only) > MPEG (identify only) > MSP > PALM (write only) > PCD (read only) > PCX > PDF (write only) > PIXAR (read only) > PNG > PPM > PSD (read only) > SGI (read only) > SPIDER > TGA (read only) > TIFF > WAL (read only) > WMF (identify only) > XBM > XPM (read only) > XV Thumbnails > > > Can any one please help in solving my problem?? > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > > <http://mail.python.org/pipermail/tutor/attachments/20080818/e7a1c2bd/attachment-0001.htm> > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From adrian.greyling at gmail.com Mon Aug 18 18:13:35 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Mon, 18 Aug 2008 12:13:35 -0400 Subject: [Tutor] Is this a "Class" problem? Message-ID: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> Hi folks! I hope I'm in the right place to ask this question. I'm new to Python and have been working through some tutorials and have made it to the GUI creation stage. All I was hoping to do with the code below, was to open a "secondary" window and have some text end up on a text_ctrl, but I get an error message that looks like this: Traceback (most recent call last): File "textbox2TEST.py", line 36, in MainToSecond MySecondFrame.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") AttributeError: type object 'MySecondFrame' has no attribute 'text_ctrl_2' I'm using wxGlade and SPE together, so almost all of the code is generated for me. I just don't get why it doesn't work, although I think it has to do with one class referencing another class, and I'm obviously not doing that correctly... Any help is much appreciated! Here's the code that created the error: import wx class MyMainFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyMainFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.button_1 = wx.Button(self, -1, "Click me to bring up second window and write some text") self.__set_properties() self.__do_layout() self.Bind(wx.EVT_BUTTON, self.MainToSecond, self.button_1) # end wxGlade def __set_properties(self): # begin wxGlade: MyMainFrame.__set_properties self.SetTitle("Main Frame") # end wxGlade def __do_layout(self): # begin wxGlade: MyMainFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_2 = wx.BoxSizer(wx.VERTICAL) sizer_2.Add(self.text_ctrl_1, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_2.Add(self.button_1, 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() # end wxGlade def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> MySecondFrame(self).Show() MySecondFrame.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") # end of class MyMainFrame class MySecondFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MySecondFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.text_ctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) self.button_2 = wx.Button(self, -1, "Click me to close this frame and send some text back to the MainFrame") self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MySecondFrame.__set_properties self.SetTitle("Frame Number Two") # end wxGlade def __do_layout(self): # begin wxGlade: MySecondFrame.__do_layout sizer_3 = wx.BoxSizer(wx.HORIZONTAL) sizer_4 = wx.BoxSizer(wx.VERTICAL) sizer_4.Add(self.text_ctrl_2, 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_4.Add(self.button_2, 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0) sizer_3.Add(sizer_4, 1, wx.EXPAND, 0) self.SetSizer(sizer_3) sizer_3.Fit(self) self.Layout() # end wxGlade # end of class MySecondFrame if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyMainFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/91c4b6b1/attachment.htm> From swati.jarial at gmail.com Mon Aug 18 18:15:14 2008 From: swati.jarial at gmail.com (swati jarial) Date: Mon, 18 Aug 2008 12:15:14 -0400 Subject: [Tutor] Timestamp Message-ID: <ac1b71c60808180915r5aa9472dq57577272342608e7@mail.gmail.com> Is there a way to put a timestamp on an FTP download in Python without using any python library or module? Thanks for any help!! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/97e0a8ee/attachment.htm> From xboxmuncher at gmail.com Mon Aug 18 18:40:34 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 18 Aug 2008 12:40:34 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2 Message-ID: <df531c470808180940v5cffa0edua9eedbdac994aa64@mail.gmail.com> I wanted to use the urllib2.https_open() but it said the module did not exist. The manual says I need SSL support installed. I've done some searching.. but I haven't been able to find an official implementation of SSL support for python 2.5 for windows. If its required for urllib2 I assume its part of the official python library of modules, is there an MSI installer or official place to get the SSL support that was mentioned in the urllib2 doc page? I just want to use the https capability of urllib2. -thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/14ec30ef/attachment.htm> From timothy.grant at gmail.com Mon Aug 18 19:12:14 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 18 Aug 2008 10:12:14 -0700 Subject: [Tutor] Timestamp In-Reply-To: <ac1b71c60808180915r5aa9472dq57577272342608e7@mail.gmail.com> References: <ac1b71c60808180915r5aa9472dq57577272342608e7@mail.gmail.com> Message-ID: <e775286d0808181012off26f9dk3d35d49fe54d18d6@mail.gmail.com> On Mon, Aug 18, 2008 at 9:15 AM, swati jarial <swati.jarial at gmail.com> wrote: > Is there a way to put a timestamp on an FTP download in Python without using > any python library or module? > > Thanks for any help!! What exactly are you trying to accomplish? The file system will stamp the file with the date it was created when you download the file. Why do you not want to use any python libraries or modules? -- Stand Fast, tjg. [Timothy Grant] From jeff at drinktomi.com Mon Aug 18 21:29:52 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Mon, 18 Aug 2008 12:29:52 -0700 Subject: [Tutor] Is this a "Class" problem? In-Reply-To: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> References: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> Message-ID: <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> On Aug 18, 2008, at 9:13 AM, Adrian Greyling wrote: > def MainToSecond(self, event): # wxGlade: > MyMainFrame.<event_handler> > MySecondFrame(self).Show() > MySecondFrame.text_ctrl_2.SetValue("This text was generated > from the 'MainFrame' window") The expression MySecondFrame(self) creates a new object. It initializes the new object by calling the MySecondFrame's __init__ method. > class MySecondFrame(wx.Frame): > def __init__(self, *args, **kwds): > # begin wxGlade: MySecondFrame.__init__ > ... > self.text_ctrl_2 = wx.TextCtrl(self, -1, "", > style=wx.TE_MULTILINE) > ... The __init__ method calls sets the variable text_ctrl_2 in the object m. Your function MainToSecond is trying to get the attribute MySecondFrame.text_ctrl_2. This attribute does not exist. You want to get the attribute m.text_ctrl_2. So, the method should be: def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> m = MySecondFrame(self) m.Show() m.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") Also, method and function names should always start with a lower case letter: always mainToSecond and never MainToSecond -jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/419ad5a0/attachment-0001.htm> From bgailer at gmail.com Mon Aug 18 22:25:05 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 18 Aug 2008 16:25:05 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2] Message-ID: <48A9DAA1.80705@gmail.com> Forwarding to the list. Please always reply to the list. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? -------------- next part -------------- An embedded message was scrubbed... From: xbmuncher <xboxmuncher at gmail.com> Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2 Date: Mon, 18 Aug 2008 12:40:34 -0400 Size: 6016 URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/52007ec4/attachment.eml> From dave6502 at googlemail.com Mon Aug 18 22:25:14 2008 From: dave6502 at googlemail.com (dave selby) Date: Mon, 18 Aug 2008 21:25:14 +0100 Subject: [Tutor] pwd lib probs Message-ID: <f52017b60808181325j1fd8b647w23e9d5ac3cdcb942@mail.gmail.com> Hi all, I am using the pwd lib where I am codeing things like ... gid = pwd.getpwnam(apache2_user)[3] where as I would like to code it as ... gid = pwd.getpwnam(apache2_user)[pwd.pw_gid] but I get gid = pwd.getpwnam(apache2_user)[pwd.pw_gid] AttributeError: 'module' object has no attribute 'pw_gid' dave at dev-system:~/kmotion2$ sudo ./install.py What am I missing ? Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From bgailer at gmail.com Mon Aug 18 22:40:13 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 18 Aug 2008 16:40:13 -0400 Subject: [Tutor] [Fwd: FW: Gaussian function] Message-ID: <48A9DE2D.6070608@gmail.com> Forwarding to the list. Please always reply to the list. It seems like you need a course on the fundamentals of programming! What output did you get? How does it differ from what you want? You define 2 functions but never call them. So they will never run. Do you know the difference? I will not write a program for you, but will, as offered, help. For starters what do the colons in the input mean? Are they decimal points? When I apply the input xmin = 2:5, dx = 0:5 and nx = 11 to the series definition xmin, xmin+dx I get 2.5 3.0 3.5 etc to infinity. Where did the -2.5 in the output come from? If you assume xmin = -2.5 then it will work. How in Python can you express this series (for loop?) What class is this question from? Have you met the prerequisites for the class? If so why is the instructor expecting you to do something he has not prepared you for? -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? -------------- next part -------------- An embedded message was scrubbed... From: Joynal Ahmed <jozzy_a at hotmail.com> Subject: FW: [Tutor] Gaussian function Date: Mon, 18 Aug 2008 19:48:01 +0100 Size: 10013 URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/0ce2a419/attachment.eml> From arsyed at gmail.com Mon Aug 18 22:57:38 2008 From: arsyed at gmail.com (arsyed) Date: Mon, 18 Aug 2008 16:57:38 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2] In-Reply-To: <48A9DAA1.80705@gmail.com> References: <48A9DAA1.80705@gmail.com> Message-ID: <9a2cc7a70808181357x6808b9e9sc8684a255f5a9cb5@mail.gmail.com> On Mon, Aug 18, 2008 at 4:25 PM, bob gailer <bgailer at gmail.com> wrote: > Forwarding to the list. Please always reply to the list. > > -- > Bob Gailer > Chapel Hill NC 919-636-4239 > > When we take the time to be aware of our feelings and needs we have more > satisfying interatctions with others. > > Nonviolent Communication provides tools for this awareness. > > As a coach and trainer I can assist you in learning this process. > > What is YOUR biggest relationship challenge? > > > I wanted to use the urllib2.https_open() but it said the module did not > exist. The manual says I need SSL support installed. I've done some > searching.. but I haven't been able to find an official implementation of > SSL support for python 2.5 for windows. If its required for urllib2 I assume > its part of the official python library of modules, is there an MSI > installer or official place to get the SSL support that was mentioned in the > urllib2 doc page? I just want to use the https capability of urllib2. > > > -thanks > Calling urlopen with an https scheme should be sufficient as long as python with SSL support is installed. I have the ActiveState Python 2.5.2 distribution on Windows XP and it seems to work fine: In [3]: response = urllib2.urlopen('https://google.com') In [4]: response = urllib2.urlopen('https://mail.google.com') In [5]: html = response.read() From john at fouhy.net Tue Aug 19 00:10:37 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 19 Aug 2008 10:10:37 +1200 Subject: [Tutor] pwd lib probs In-Reply-To: <f52017b60808181325j1fd8b647w23e9d5ac3cdcb942@mail.gmail.com> References: <f52017b60808181325j1fd8b647w23e9d5ac3cdcb942@mail.gmail.com> Message-ID: <5e58f2e40808181510v1eb368b6h9fa6c9d25f7359d1@mail.gmail.com> 2008/8/19 dave selby <dave6502 at googlemail.com>: > Hi all, > > I am using the pwd lib where I am codeing things like ... > > gid = pwd.getpwnam(apache2_user)[3] > > where as I would like to code it as ... > > gid = pwd.getpwnam(apache2_user)[pwd.pw_gid] > > but I get > > gid = pwd.getpwnam(apache2_user)[pwd.pw_gid] > AttributeError: 'module' object has no attribute 'pw_gid' > dave at dev-system:~/kmotion2$ sudo ./install.py > > What am I missing ? I haven't used the pwd module, but at a guess, maybe you should type: gid = pwd.getpwnam(apache2_user).pw_gid -- John. From robert.johansson at math.umu.se Tue Aug 19 00:17:34 2008 From: robert.johansson at math.umu.se (Robert Johansson) Date: Tue, 19 Aug 2008 00:17:34 +0200 Subject: [Tutor] unsupported characters In-Reply-To: <1c2a2c590808171353x5a4d7409t105edcdf2eb06e23@mail.gmail.com> References: <1214103052798061254@unknownmsgid> <1c2a2c590808171353x5a4d7409t105edcdf2eb06e23@mail.gmail.com> Message-ID: <005b01c90180$39e413a0$adac3ae0$@johansson@math.umu.se> On 8/17/08, Robert Johansson <robert.johansson at math.umu.se> wrote: > Hi, I have problems using characters from the Swedish language. I tried the > following in IDLE under MacOS X leopard (running Python 2.5.1) : > S='?' > Displaying error message: "unsupported characters in input". To use non-ascii characters in Python code you have to declare the encoding of the source file with a comment such as # coding=UTF-8 See http://python.org/dev/peps/pep-0263/ Kent Thanks for taking you time with this. Yes, that works. I know that you can declare the encoding for a script in that way but there is still a problem when I use the shell as input device. There are options for encoding in the menu for IDLE but changing them doesn't help at all. I've tried two versions of IDLE but both seem to be a bit buggy (scrolling doesn?t work, etc). If there are any Mac users who read this, which editor would you recommend for Mac? /Robert From jozzy_a at hotmail.com Mon Aug 18 22:30:13 2008 From: jozzy_a at hotmail.com (optimum) Date: Mon, 18 Aug 2008 13:30:13 -0700 (PDT) Subject: [Tutor] Gaussian function In-Reply-To: <48A89796.6090300@gmail.com> References: <19022946.post@talk.nabble.com> <48A89796.6090300@gmail.com> Message-ID: <19039434.post@talk.nabble.com> I dont think that this program uses the gaussian function, am I in the right wavelength? from __future__ import division import math a=raw_input("What is the value of xmin?") b=raw_input("What is the value of dx?") c=raw_input("What is the value of nx?") xmin=float(a) dx=float(b) nx=int(c) n=int(c) l=[] for x in range(0.00,n): print xmin+x*dx def line(n): s='' i=raw_input("Please choose a scale for your plot") n=int(i) for j in range(0.00,n): s= s+ "***" + "\n" print s return s def gauss(x): gaussa=math.pi(2) gaussb=math.sqrt(gaussa) gaussc=1/gaussb gaussd=math.exp(-0.5*-2.00**2) gausse= gaussc*gaussd print gausse Bob Gailer wrote: > > optimum wrote: >> Hey. Is there anyone who can give me some help? >> Below is the question I was set. >> > This sounds like a homework assignment. We don't write programs for > assignments. We offer help after you give it your best effort. >> I am having trouble with the gaussian function and don't really know >> where >> to start. >> > > It sounds like you are having trouble with programming, not with the > gaussian function. Did you run the following code? Did it give you any > useful results? (I expect it to raise an exception.) At least run it and > see what happens. How does it contribute to the overall result? > > s='' > for n in range (0,100): > s=s+ '*' > print s > > > Can you at least outline the program or algorithm as a starting place. >> "Write a program which asks the user for values >> of xmin, dx and nx. The program should then >> output a plot of the gaussian function >> >> >> at the following series of values of x: >> xmin, xmin+dx, xmin+2*dx, xmin+3*dx, : : :, >> xmin+(nx-1)*dx. e.g. the following output >> should result if xmin = 2:5, dx = 0:5 and >> nx = 11. >> -2.50 * >> -2.00 *** >> -1.50 ****** >> -1.00 ************ >> -0.50 ****************** >> 0.00 ******************** >> 0.50 ****************** >> 1.00 ************ >> 1.50 ****** >> 2.00 *** >> 2.50 * >> The program should contain and make full use >> of the following functions: >> gauss(x) - Returns the value of the Gaussian >> function >> >> line(n) - Prints a line of n asterisks followed >> by a newline character. >> >> You will need to choose a scale for your plot; >> in the example shown the number of asterisks >> is 50 * gauss(x). >> >> Should I start with a program like this? >> >> s='' >> for n in range (0,100): >> s=s+ '*' >> print s >> >> Thanks for any help received. :confused: >> > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > > When we take the time to be aware of our feelings and > needs we have more satisfying interatctions with others. > > Nonviolent Communication provides tools for this awareness. > > As a coach and trainer I can assist you in learning this process. > > What is YOUR biggest relationship challenge? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Gaussian-function-tp19022946p19039434.html Sent from the Python - tutor mailing list archive at Nabble.com. From jozzy_a at hotmail.com Mon Aug 18 23:05:10 2008 From: jozzy_a at hotmail.com (optimum) Date: Mon, 18 Aug 2008 14:05:10 -0700 (PDT) Subject: [Tutor] Gaussian function In-Reply-To: <19039434.post@talk.nabble.com> References: <19022946.post@talk.nabble.com> <48A89796.6090300@gmail.com> <19039434.post@talk.nabble.com> Message-ID: <19039962.post@talk.nabble.com> SOrry, just started python programming. I have so much to learn still. My output was What is the value of xmin?-2.5 What is the value of dx?0.5 What is the value of nx?11 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 Please choose a scale for your plot50 * I think I called the functions now...but I don't get the desired output, is it my gaussian function which is wrong? We had a lecture on "def" function, but wasn't really told how to do this program. from __future__ import division import math a=raw_input("What is the value of xmin?") b=raw_input("What is the value of dx?") c=raw_input("What is the value of nx?") xmin=float(a) dx=float(b) nx=int(c) n=int(c) l=[] for x in range(0.00,n): print xmin+x*dx def line(n): s='' i=raw_input("Please choose a scale for your plot") n=int(i) for j in range(0.00,n): s= s+ "*" + "\n" print s return s def gauss(x): gaussa=math.pi(2) gaussb=math.sqrt(gaussa) gaussc=1/gaussb gaussd=math.exp(-0.5*-2.00**2) gausse= gaussc*gaussd return gausse print gausse line(gauss) optimum wrote: > > I dont think that this program uses the gaussian function, am I in the > right wavelength? > > from __future__ import division > import math > > a=raw_input("What is the value of xmin?") > b=raw_input("What is the value of dx?") > c=raw_input("What is the value of nx?") > > xmin=float(a) > dx=float(b) > nx=int(c) > n=int(c) > l=[] > > for x in range(0.00,n): > print xmin+x*dx > def line(n): > s='' > i=raw_input("Please choose a scale for your plot") > n=int(i) > for j in range(0.00,n): > s= s+ "***" + "\n" > print s > return s > > def gauss(x): > gaussa=math.pi(2) > gaussb=math.sqrt(gaussa) > gaussc=1/gaussb > gaussd=math.exp(-0.5*-2.00**2) > gausse= gaussc*gaussd > print gausse > > > > Bob Gailer wrote: >> >> optimum wrote: >>> Hey. Is there anyone who can give me some help? >>> Below is the question I was set. >>> >> This sounds like a homework assignment. We don't write programs for >> assignments. We offer help after you give it your best effort. >>> I am having trouble with the gaussian function and don't really know >>> where >>> to start. >>> >> >> It sounds like you are having trouble with programming, not with the >> gaussian function. Did you run the following code? Did it give you any >> useful results? (I expect it to raise an exception.) At least run it and >> see what happens. How does it contribute to the overall result? >> >> s='' >> for n in range (0,100): >> s=s+ '*' >> print s >> >> >> Can you at least outline the program or algorithm as a starting place. >>> "Write a program which asks the user for values >>> of xmin, dx and nx. The program should then >>> output a plot of the gaussian function >>> >>> >>> at the following series of values of x: >>> xmin, xmin+dx, xmin+2*dx, xmin+3*dx, : : :, >>> xmin+(nx-1)*dx. e.g. the following output >>> should result if xmin = 2:5, dx = 0:5 and >>> nx = 11. >>> -2.50 * >>> -2.00 *** >>> -1.50 ****** >>> -1.00 ************ >>> -0.50 ****************** >>> 0.00 ******************** >>> 0.50 ****************** >>> 1.00 ************ >>> 1.50 ****** >>> 2.00 *** >>> 2.50 * >>> The program should contain and make full use >>> of the following functions: >>> gauss(x) - Returns the value of the Gaussian >>> function >>> >>> line(n) - Prints a line of n asterisks followed >>> by a newline character. >>> >>> You will need to choose a scale for your plot; >>> in the example shown the number of asterisks >>> is 50 * gauss(x). >>> >>> Should I start with a program like this? >>> >>> s='' >>> for n in range (0,100): >>> s=s+ '*' >>> print s >>> >>> Thanks for any help received. :confused: >>> >> >> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 >> >> When we take the time to be aware of our feelings and >> needs we have more satisfying interatctions with others. >> >> Nonviolent Communication provides tools for this awareness. >> >> As a coach and trainer I can assist you in learning this process. >> >> What is YOUR biggest relationship challenge? >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > -- View this message in context: http://www.nabble.com/Gaussian-function-tp19022946p19039962.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Tue Aug 19 02:44:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Aug 2008 20:44:36 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2 In-Reply-To: <df531c470808180940v5cffa0edua9eedbdac994aa64@mail.gmail.com> References: <df531c470808180940v5cffa0edua9eedbdac994aa64@mail.gmail.com> Message-ID: <1c2a2c590808181744v6e098393o926b8dea1501f83e@mail.gmail.com> On Mon, Aug 18, 2008 at 12:40 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > I wanted to use the urllib2.https_open() but it said the module did not > exist. I'm not aware of a urllib2.https_open() function. I think you just give an https url to urllib2.urlopen(). Can you show us your actual code and error message? Kent From kent37 at tds.net Tue Aug 19 02:57:57 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Aug 2008 20:57:57 -0400 Subject: [Tutor] unsupported characters In-Reply-To: <4991163467152737984@unknownmsgid> References: <1214103052798061254@unknownmsgid> <1c2a2c590808171353x5a4d7409t105edcdf2eb06e23@mail.gmail.com> <4991163467152737984@unknownmsgid> Message-ID: <1c2a2c590808181757m76656c23i9cade54f6f553ece@mail.gmail.com> On Mon, Aug 18, 2008 at 6:17 PM, Robert Johansson <robert.johansson at math.umu.se> wrote: > If > there are any Mac users who read this, which editor would you recommend for > Mac? TextMate is very popular, it is my choice. For Python programs that require console input, run them in Terminal. Personally I don't think much of IDLE; it's chief advantage is that it is better than Notepad or TextEdit. I have Terminal set to use UTF-8 encoding and I can input and print non-ascii characters in Python 2.5.2: In [2]: s='?' In [3]: s Out[3]: '\xc3\xb6' In [4]: print s ? Kent From bgailer at gmail.com Tue Aug 19 03:25:51 2008 From: bgailer at gmail.com (bob gailer) Date: Mon, 18 Aug 2008 21:25:51 -0400 Subject: [Tutor] Gaussian function In-Reply-To: <19039962.post@talk.nabble.com> References: <19022946.post@talk.nabble.com> <48A89796.6090300@gmail.com> <19039434.post@talk.nabble.com> <19039962.post@talk.nabble.com> Message-ID: <48AA211F.2060206@gmail.com> optimum wrote: > SOrry, just started python programming. I have so much to learn still. > My output was > What is the value of xmin?-2.5 > What is the value of dx?0.5 > What is the value of nx?11 > -2.5 > -2.0 > -1.5 > -1.0 > -0.5 > 0.0 > 0.5 > 1.0 > 1.5 > 2.0 > 2.5 > Please choose a scale for your plot50 > * > > I think I called the functions now...but I don't get the desired output, is > it my gaussian function which is wrong? > We had a lecture on "def" function What did you learn from that lecture? > but wasn't really told how to do this program. > As I pointed out in Experts Exchange the assignment is too complex for your current understanding of Python! -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From xboxmuncher at gmail.com Tue Aug 19 03:26:19 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 18 Aug 2008 21:26:19 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2 In-Reply-To: <1c2a2c590808181744v6e098393o926b8dea1501f83e@mail.gmail.com> References: <df531c470808180940v5cffa0edua9eedbdac994aa64@mail.gmail.com> <1c2a2c590808181744v6e098393o926b8dea1501f83e@mail.gmail.com> Message-ID: <df531c470808181826t512b47dcye58dc4288469de16@mail.gmail.com> On Mon, Aug 18, 2008 at 8:44 PM, Kent Johnson <kent37 at tds.net> wrote: > On Mon, Aug 18, 2008 at 12:40 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > > I wanted to use the urllib2.https_open() but it said the module did not > > exist. > > I'm not aware of a urllib2.https_open() function. I think you just > give an https url to urllib2.urlopen(). Can you show us your actual > code and error message? > > Kent > http://docs.python.org/lib/https-handler-objects.html I accessed it like this: urllib2.https_open(req) Its probably the syntax formation of using this https functionality that I have wrong. Maybe you can show me how. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/6e1442c2/attachment.htm> From xboxmuncher at gmail.com Tue Aug 19 03:36:52 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 18 Aug 2008 21:36:52 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2] In-Reply-To: <9a2cc7a70808181357x6808b9e9sc8684a255f5a9cb5@mail.gmail.com> References: <48A9DAA1.80705@gmail.com> <9a2cc7a70808181357x6808b9e9sc8684a255f5a9cb5@mail.gmail.com> Message-ID: <df531c470808181836g7c297630m8e9d28f0b2c71ca9@mail.gmail.com> I tried it just like both of you suggested and sent a req object straight to urlopen. Here is my code: import urllib2 url = 'https://url.com' headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', 'Accept' : 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language' : 'fr-fr,en-us;q=0.7,en;q=0.3', 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' } #None = GET; set values to use POST req = urllib2.Request(url, None, headers) handle = urllib2.urlopen(req) resp = handle.read() print resp.geturl() print resp.info() print resp resp.close() Here is the error msg: Traceback (most recent call last): File "C:\Documents and Settings\user\Desktop\https_query.py", line 16, in <module> handle = urllib2.urlopen(req) File "C:\Python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1115, in https_open return self.do_open(httplib.HTTPSConnection, req) File "C:\Python25\lib\urllib2.py", line 1080, in do_open r = h.getresponse() File "C:\Python25\lib\httplib.py", line 928, in getresponse response.begin() File "C:\Python25\lib\httplib.py", line 385, in begin version, status, reason = self._read_status() File "C:\Python25\lib\httplib.py", line 349, in _read_status raise BadStatusLine(line) BadStatusLine >>> On Mon, Aug 18, 2008 at 4:57 PM, arsyed <arsyed at gmail.com> wrote: > On Mon, Aug 18, 2008 at 4:25 PM, bob gailer <bgailer at gmail.com> wrote: > > Forwarding to the list. Please always reply to the list. > > > > -- > > Bob Gailer > > Chapel Hill NC 919-636-4239 > > > > When we take the time to be aware of our feelings and needs we have more > > satisfying interatctions with others. > > > > Nonviolent Communication provides tools for this awareness. > > > > As a coach and trainer I can assist you in learning this process. > > > > What is YOUR biggest relationship challenge? > > > > > > I wanted to use the urllib2.https_open() but it said the module did not > > exist. The manual says I need SSL support installed. I've done some > > searching.. but I haven't been able to find an official implementation of > > SSL support for python 2.5 for windows. If its required for urllib2 I > assume > > its part of the official python library of modules, is there an MSI > > installer or official place to get the SSL support that was mentioned in > the > > urllib2 doc page? I just want to use the https capability of urllib2. > > > > > > -thanks > > > > > Calling urlopen with an https scheme should be sufficient as long as > python with SSL support is installed. I have the ActiveState Python > 2.5.2 distribution on Windows XP and it seems to work fine: > > In [3]: response = urllib2.urlopen('https://google.com') > > In [4]: response = urllib2.urlopen('https://mail.google.com') > > In [5]: html = response.read() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080818/493963f9/attachment-0001.htm> From john.destefano at gmail.com Tue Aug 19 04:40:25 2008 From: john.destefano at gmail.com (John DeStefano) Date: Mon, 18 Aug 2008 22:40:25 -0400 Subject: [Tutor] Python proxy settings in OS X Message-ID: <EB0A695F-1B63-4033-8655-2FA10AC8CBD6@gmail.com> I'm having trouble with OS X proxy settings and getting Python to ignore them. I have multiple Python installations on my system: /opt/local/bin/python (2.5.1) /usr/local/bin/2.3 /opt/local/bin/2.4 /usr/bin/python244 (2.4.4) /opt/local/bin/2.5 I've noticed that when using some of these versions, my scripts that make web calls work fine, but the same scripts die with timeouts using other versions. I thought Python simply read and respected 'env' settings, but clearing these in my session doesn't seem to help. As a result, I have even tried to remove my proxy settings entirely, but that is another, off-topic story [1]. Where all these installations came from, I'm not entirely sure. I know I had to install a copy of 2.4, and I must have used 'ports' for some version. At some point, I would like to clean these up and have only one copy of each version installed, but I'm not sure which versions would screw things up if they were to be removed. Thanks for your help in understanding Python and proxy settings, and how to fix settings if possible. Thank you, ~John [1] http://forums.macosxhints.com/showthread.php?t=93086 From arsyed at gmail.com Tue Aug 19 10:36:08 2008 From: arsyed at gmail.com (arsyed) Date: Tue, 19 Aug 2008 04:36:08 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2] In-Reply-To: <df531c470808181836g7c297630m8e9d28f0b2c71ca9@mail.gmail.com> References: <48A9DAA1.80705@gmail.com> <9a2cc7a70808181357x6808b9e9sc8684a255f5a9cb5@mail.gmail.com> <df531c470808181836g7c297630m8e9d28f0b2c71ca9@mail.gmail.com> Message-ID: <9a2cc7a70808190136r500dccftbcdc1297ffda5db0@mail.gmail.com> On Mon, Aug 18, 2008 at 9:36 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > I tried it just like both of you suggested and sent a req object straight to > urlopen. Here is my code: > import urllib2 > url = 'https://url.com' > headers = { > 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', > 'Accept' : > 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', > 'Accept-Language' : 'fr-fr,en-us;q=0.7,en;q=0.3', > 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' > } > > #None = GET; set values to use POST > req = urllib2.Request(url, None, headers) > handle = urllib2.urlopen(req) > resp = handle.read() > print resp.geturl() > print resp.info() > print resp > > resp.close() > > > > Here is the error msg: > Traceback (most recent call last): > File "C:\Documents and Settings\user\Desktop\https_query.py", line 16, in > <module> > handle = urllib2.urlopen(req) > File "C:\Python25\lib\urllib2.py", line 124, in urlopen > return _opener.open(url, data) > File "C:\Python25\lib\urllib2.py", line 381, in open > response = self._open(req, data) > File "C:\Python25\lib\urllib2.py", line 399, in _open > '_open', req) > File "C:\Python25\lib\urllib2.py", line 360, in _call_chain > result = func(*args) > File "C:\Python25\lib\urllib2.py", line 1115, in https_open > return self.do_open(httplib.HTTPSConnection, req) > File "C:\Python25\lib\urllib2.py", line 1080, in do_open > r = h.getresponse() > File "C:\Python25\lib\httplib.py", line 928, in getresponse > response.begin() > File "C:\Python25\lib\httplib.py", line 385, in begin > version, status, reason = self._read_status() > File "C:\Python25\lib\httplib.py", line 349, in _read_status > raise BadStatusLine(line) > BadStatusLine What URL are you trying this against? The URL in your code "https://url.com" doesn't seem to respond at all so I can't reproduce your error. Have you tried against a well known HTTPS endpoint like "https://mail.google.com"? What happens? I'll try to guess anyway .. the Status Line in an HTTP response is the first line that gives the response code, something like "HTTP/1.1 200 OK". Maybe your server is returning malformed headers? See below for more: http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html From scsoce at gmail.com Tue Aug 19 10:38:31 2008 From: scsoce at gmail.com (scsoce) Date: Tue, 19 Aug 2008 16:38:31 +0800 Subject: [Tutor] how to read Messages sorted by thread in thunderbird In-Reply-To: <mailman.18881.1219109825.920.tutor@python.org> References: <mailman.18881.1219109825.920.tutor@python.org> Message-ID: <48AA8687.1050407@gmail.com> 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: unsupported characters (Robert Johansson) > 2. Re: Gaussian function (optimum) > 3. Re: Gaussian function (optimum) > 4. Re: How to use urllib2.https_open with SSL support in Windows > XP for python 2.5.2 (Kent Johnson) > 5. Re: unsupported characters (Kent Johnson) > 6. Re: Gaussian function (bob gailer) > 7. Re: How to use urllib2.https_open with SSL support in Windows > XP for python 2.5.2 (xbmuncher) > 8. Re: How to use urllib2.https_open with SSL support in Windows > XP for python 2.5.2] (xbmuncher) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 19 Aug 2008 00:17:34 +0200 > From: "Robert Johansson" <robert.johansson at math.umu.se> > Subject: Re: [Tutor] unsupported characters > To: "'Kent Johnson'" <kent37 at tds.net> > Cc: Tutor at python.org > Message-ID: <005b01c90180$39e413a0$adac3ae0$@johansson at math.umu.se> > Content-Type: text/plain; charset="iso-8859-1" > > On 8/17/08, Robert Johansson <robert.johansson at math.umu.se> wrote: > > >> Hi, I have problems using characters from the Swedish language. I tried >> > the > >> following in IDLE under MacOS X leopard (running Python 2.5.1) : >> > > >> S='?' >> Displaying error message: "unsupported characters in input". >> > > To use non-ascii characters in Python code you have to declare the > encoding of the source file with a comment such as > # coding=UTF-8 > > See http://python.org/dev/peps/pep-0263/ > > Kent > > Thanks for taking you time with this. Yes, that works. I know that you can > declare the encoding for a script in that way but there is still a problem > when I use the shell as input device. There are options for encoding in the > menu for IDLE but changing them doesn't help at all. I've tried two versions > of IDLE but both seem to be a bit buggy (scrolling doesn?t work, etc). If > there are any Mac users who read this, which editor would you recommend for > Mac? > > /Robert > > > > ------------------------------ > > Message: 2 > Date: Mon, 18 Aug 2008 13:30:13 -0700 (PDT) > From: optimum <jozzy_a at hotmail.com> > Subject: Re: [Tutor] Gaussian function > To: tutor at python.org > Message-ID: <19039434.post at talk.nabble.com> > Content-Type: text/plain; charset=us-ascii > > > I dont think that this program uses the gaussian function, am I in the right > wavelength? > > from __future__ import division > import math > > a=raw_input("What is the value of xmin?") > b=raw_input("What is the value of dx?") > c=raw_input("What is the value of nx?") > > xmin=float(a) > dx=float(b) > nx=int(c) > n=int(c) > l=[] > > for x in range(0.00,n): > print xmin+x*dx > def line(n): > s='' > i=raw_input("Please choose a scale for your plot") > n=int(i) > for j in range(0.00,n): > s= s+ "***" + "\n" > print s > return s > > def gauss(x): > gaussa=math.pi(2) > gaussb=math.sqrt(gaussa) > gaussc=1/gaussb > gaussd=math.exp(-0.5*-2.00**2) > gausse= gaussc*gaussd > print gausse > > > > Bob Gailer wrote: > >> optimum wrote: >> >>> Hey. Is there anyone who can give me some help? >>> Below is the question I was set. >>> >>> >> This sounds like a homework assignment. We don't write programs for >> assignments. We offer help after you give it your best effort. >> >>> I am having trouble with the gaussian function and don't really know >>> where >>> to start. >>> >>> >> It sounds like you are having trouble with programming, not with the >> gaussian function. Did you run the following code? Did it give you any >> useful results? (I expect it to raise an exception.) At least run it and >> see what happens. How does it contribute to the overall result? >> >> s='' >> for n in range (0,100): >> s=s+ '*' >> print s >> >> >> Can you at least outline the program or algorithm as a starting place. >> >>> "Write a program which asks the user for values >>> of xmin, dx and nx. The program should then >>> output a plot of the gaussian function >>> >>> >>> at the following series of values of x: >>> xmin, xmin+dx, xmin+2*dx, xmin+3*dx, : : :, >>> xmin+(nx-1)*dx. e.g. the following output >>> should result if xmin = 2:5, dx = 0:5 and >>> nx = 11. >>> -2.50 * >>> -2.00 *** >>> -1.50 ****** >>> -1.00 ************ >>> -0.50 ****************** >>> 0.00 ******************** >>> 0.50 ****************** >>> 1.00 ************ >>> 1.50 ****** >>> 2.00 *** >>> 2.50 * >>> The program should contain and make full use >>> of the following functions: >>> gauss(x) - Returns the value of the Gaussian >>> function >>> >>> line(n) - Prints a line of n asterisks followed >>> by a newline character. >>> >>> You will need to choose a scale for your plot; >>> in the example shown the number of asterisks >>> is 50 * gauss(x). >>> >>> Should I start with a program like this? >>> >>> s='' >>> for n in range (0,100): >>> s=s+ '*' >>> print s >>> >>> Thanks for any help received. :confused: >>> >>> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 >> >> When we take the time to be aware of our feelings and >> needs we have more satisfying interatctions with others. >> >> Nonviolent Communication provides tools for this awareness. >> >> As a coach and trainer I can assist you in learning this process. >> >> What is YOUR biggest relationship challenge? >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > hello, guys: Sorry to ask a question not related to python, but to the mail list. That is i use thundbird to read the list, just find when a post with many threads is clustered and unfriendly to me. My question is there a way to read messages sorted by thread ( just like in web version http://mail.python.org/pipermail/ ) but in thunderbird or other mail applications, or other way better ? thks --song * * From arsyed at gmail.com Tue Aug 19 10:39:30 2008 From: arsyed at gmail.com (arsyed) Date: Tue, 19 Aug 2008 04:39:30 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2 In-Reply-To: <df531c470808181826t512b47dcye58dc4288469de16@mail.gmail.com> References: <df531c470808180940v5cffa0edua9eedbdac994aa64@mail.gmail.com> <1c2a2c590808181744v6e098393o926b8dea1501f83e@mail.gmail.com> <df531c470808181826t512b47dcye58dc4288469de16@mail.gmail.com> Message-ID: <9a2cc7a70808190139g50d6a215l9b6abfffe6ed5da6@mail.gmail.com> On Mon, Aug 18, 2008 at 9:26 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > > > On Mon, Aug 18, 2008 at 8:44 PM, Kent Johnson <kent37 at tds.net> wrote: >> >> On Mon, Aug 18, 2008 at 12:40 PM, xbmuncher <xboxmuncher at gmail.com> wrote: >> > I wanted to use the urllib2.https_open() but it said the module did not >> > exist. >> >> I'm not aware of a urllib2.https_open() function. I think you just >> give an https url to urllib2.urlopen(). Can you show us your actual >> code and error message? >> >> Kent > > http://docs.python.org/lib/https-handler-objects.html > I accessed it like this: > urllib2.https_open(req) > > Its probably the syntax formation of using this https functionality that I > have wrong. Maybe you can show me how. > That method is part of the HTTPSHandler class as the docs page you cited implies. I believe this is what urllib2.urlopen instantiates once it parses your URL and notices the "https" scheme. You don't need to instantiate that handler and invoke that method directly. From alan.gauld at btinternet.com Tue Aug 19 11:01:04 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Aug 2008 10:01:04 +0100 Subject: [Tutor] how to read Messages sorted by thread in thunderbird References: <mailman.18881.1219109825.920.tutor@python.org> <48AA8687.1050407@gmail.com> Message-ID: <g8e24j$ssi$1@ger.gmane.org> "scsoce" <scsoce at gmail.com> wrote > many threads is clustered and unfriendly to me. My question is > there a way to read messages sorted by thread ( just like in web > version http://mail.python.org/pipermail/ ) but in thunderbird or > other mail applications, or other way better ? I mainly use Outlook Express as a newsreader and access the list via the gmane archive. That gives me threading as well as all the other features of news reading - watched threads, kill lists etc I'm not sure if Thunderbird does n news feeds or is purely email based? But it might be an option. The snag is that there is occasionally a short delay between the email going out and its appearance on gmabe, but its usually insignificant. HTH, Alan G. From timothy.grant at gmail.com Tue Aug 19 11:48:39 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Tue, 19 Aug 2008 02:48:39 -0700 Subject: [Tutor] how to read Messages sorted by thread in thunderbird In-Reply-To: <48AA8687.1050407@gmail.com> References: <mailman.18881.1219109825.920.tutor@python.org> <48AA8687.1050407@gmail.com> Message-ID: <e775286d0808190248g2fed543dj8a3f87ff857100a5@mail.gmail.com> On Tue, Aug 19, 2008 at 1:38 AM, scsoce <scsoce at gmail.com> wrote: > 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: unsupported characters (Robert Johansson) >> 2. Re: Gaussian function (optimum) >> 3. Re: Gaussian function (optimum) >> 4. Re: How to use urllib2.https_open with SSL support in Windows >> XP for python 2.5.2 (Kent Johnson) >> 5. Re: unsupported characters (Kent Johnson) >> 6. Re: Gaussian function (bob gailer) >> 7. Re: How to use urllib2.https_open with SSL support in Windows >> XP for python 2.5.2 (xbmuncher) >> 8. Re: How to use urllib2.https_open with SSL support in Windows >> XP for python 2.5.2] (xbmuncher) >> >> >> ---------------------------------------------------------------------- >> >> Message: 1 >> Date: Tue, 19 Aug 2008 00:17:34 +0200 >> From: "Robert Johansson" <robert.johansson at math.umu.se> >> Subject: Re: [Tutor] unsupported characters >> To: "'Kent Johnson'" <kent37 at tds.net> >> Cc: Tutor at python.org >> Message-ID: <005b01c90180$39e413a0$adac3ae0$@johansson at math.umu.se> >> Content-Type: text/plain; charset="iso-8859-1" >> >> On 8/17/08, Robert Johansson <robert.johansson at math.umu.se> wrote: >> >> >>> >>> Hi, I have problems using characters from the Swedish language. I tried >>> >> >> the >> >>> >>> following in IDLE under MacOS X leopard (running Python 2.5.1) : >>> >> >> >>> >>> S='?' >>> Displaying error message: "unsupported characters in input". >>> >> >> To use non-ascii characters in Python code you have to declare the >> encoding of the source file with a comment such as >> # coding=UTF-8 >> >> See http://python.org/dev/peps/pep-0263/ >> >> Kent >> >> Thanks for taking you time with this. Yes, that works. I know that you can >> declare the encoding for a script in that way but there is still a problem >> when I use the shell as input device. There are options for encoding in >> the >> menu for IDLE but changing them doesn't help at all. I've tried two >> versions >> of IDLE but both seem to be a bit buggy (scrolling doesn?t work, etc). If >> there are any Mac users who read this, which editor would you recommend >> for >> Mac? >> /Robert >> >> >> >> ------------------------------ >> >> Message: 2 >> Date: Mon, 18 Aug 2008 13:30:13 -0700 (PDT) >> From: optimum <jozzy_a at hotmail.com> >> Subject: Re: [Tutor] Gaussian function >> To: tutor at python.org >> Message-ID: <19039434.post at talk.nabble.com> >> Content-Type: text/plain; charset=us-ascii >> >> >> I dont think that this program uses the gaussian function, am I in the >> right >> wavelength? >> from __future__ import division >> import math >> >> a=raw_input("What is the value of xmin?") >> b=raw_input("What is the value of dx?") >> c=raw_input("What is the value of nx?") >> >> xmin=float(a) >> dx=float(b) >> nx=int(c) >> n=int(c) >> l=[] >> >> for x in range(0.00,n): >> print xmin+x*dx >> def line(n): >> s='' >> i=raw_input("Please choose a scale for your plot") >> n=int(i) >> for j in range(0.00,n): >> s= s+ "***" + "\n" >> print s >> return s >> def gauss(x): >> gaussa=math.pi(2) >> gaussb=math.sqrt(gaussa) >> gaussc=1/gaussb >> gaussd=math.exp(-0.5*-2.00**2) >> gausse= gaussc*gaussd >> print gausse >> >> >> >> Bob Gailer wrote: >> >>> >>> optimum wrote: >>> >>>> >>>> Hey. Is there anyone who can give me some help? Below is the question I >>>> was set. >>>> >>> >>> This sounds like a homework assignment. We don't write programs for >>> assignments. We offer help after you give it your best effort. >>> >>>> >>>> I am having trouble with the gaussian function and don't really know >>>> where >>>> to start. >>>> >>> >>> It sounds like you are having trouble with programming, not with the >>> gaussian function. Did you run the following code? Did it give you any >>> useful results? (I expect it to raise an exception.) At least run it and see >>> what happens. How does it contribute to the overall result? >>> >>> s='' >>> for n in range (0,100): >>> s=s+ '*' >>> print s >>> >>> >>> Can you at least outline the program or algorithm as a starting place. >>> >>>> >>>> "Write a program which asks the user for values >>>> of xmin, dx and nx. The program should then >>>> output a plot of the gaussian function >>>> >>>> >>>> at the following series of values of x: >>>> xmin, xmin+dx, xmin+2*dx, xmin+3*dx, : : :, >>>> xmin+(nx-1)*dx. e.g. the following output >>>> should result if xmin = 2:5, dx = 0:5 and >>>> nx = 11. >>>> -2.50 * >>>> -2.00 *** >>>> -1.50 ****** >>>> -1.00 ************ >>>> -0.50 ****************** >>>> 0.00 ******************** >>>> 0.50 ****************** >>>> 1.00 ************ >>>> 1.50 ****** >>>> 2.00 *** >>>> 2.50 * >>>> The program should contain and make full use >>>> of the following functions: >>>> gauss(x) - Returns the value of the Gaussian >>>> function >>>> >>>> line(n) - Prints a line of n asterisks followed >>>> by a newline character. >>>> >>>> You will need to choose a scale for your plot; >>>> in the example shown the number of asterisks >>>> is 50 * gauss(x). >>>> >>>> Should I start with a program like this? >>>> >>>> s='' >>>> for n in range (0,100): >>>> s=s+ '*' >>>> print s >>>> >>>> Thanks for any help received. :confused: >>>> >>> >>> -- >>> Bob Gailer >>> Chapel Hill NC 919-636-4239 >>> >>> When we take the time to be aware of our feelings and needs we have more >>> satisfying interatctions with others. >>> >>> Nonviolent Communication provides tools for this awareness. >>> >>> As a coach and trainer I can assist you in learning this process. >>> >>> What is YOUR biggest relationship challenge? >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> > > hello, guys: > > Sorry to ask a question not related to python, but to the mail list. That > is i use thundbird to read the list, just find when a post with many > threads is clustered and unfriendly to me. My question is there a way to > read messages sorted by thread ( just like in web version > http://mail.python.org/pipermail/ ) but in thunderbird or other mail > applications, or other way better ? > thks > --song * > * > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Looks to me like you might be subscribed to the digest instead of individual messages. If you're subscribed to the digest, you likely have to read the messages in the order the digest provides them. -- Stand Fast, tjg. [Timothy Grant] From kent37 at tds.net Tue Aug 19 12:36:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Aug 2008 06:36:29 -0400 Subject: [Tutor] How to use urllib2.https_open with SSL support in Windows XP for python 2.5.2] In-Reply-To: <df531c470808181836g7c297630m8e9d28f0b2c71ca9@mail.gmail.com> References: <48A9DAA1.80705@gmail.com> <9a2cc7a70808181357x6808b9e9sc8684a255f5a9cb5@mail.gmail.com> <df531c470808181836g7c297630m8e9d28f0b2c71ca9@mail.gmail.com> Message-ID: <1c2a2c590808190336l3b43debbg95db9064d0a4a58d@mail.gmail.com> On Mon, Aug 18, 2008 at 9:36 PM, xbmuncher <xboxmuncher at gmail.com> wrote: > I tried it just like both of you suggested and sent a req object straight to > urlopen. Here is my code: > import urllib2 > url = 'https://url.com' > headers = { > 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', > 'Accept' : > 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', > 'Accept-Language' : 'fr-fr,en-us;q=0.7,en;q=0.3', > 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' > } > > #None = GET; set values to use POST > req = urllib2.Request(url, None, headers) > handle = urllib2.urlopen(req) > resp = handle.read() > print resp.geturl() > print resp.info() > print resp > > resp.close() > > > > Here is the error msg: > Traceback (most recent call last): > > File "C:\Python25\lib\httplib.py", line 349, in _read_status > raise BadStatusLine(line) > BadStatusLine Looking at the source for httplib, that error is raised when no status line response is received from the host. Are you sure you are using a correct URL? Kent From tetsuo2k6 at web.de Tue Aug 19 15:16:44 2008 From: tetsuo2k6 at web.de (Paul Schewietzek) Date: Tue, 19 Aug 2008 15:16:44 +0200 Subject: [Tutor] FTP question (slightly OT) Message-ID: <1219151804.5451.23.camel@tetsuo.powmark.local> Hello everyone, I put together the following, most of it is from different howtos on the web. <code> #!/usr/bin/env python # -*- coding: utf-8 -*- def gettext(ftp, filename, outfile=None): if outfile is None: outfile = sys.stdout ftp.retrlines("RETR %s" % filename, lambda s, w=outfile.write: w(s+"\n")) def main(): from ftplib import FTP import datetime ftp = FTP("ftp.ftpserver.com") ftp.login("my_username", "my_passwd") ftp.set_pasv(1) filename = "name_of_textfile" outfile = open(filename, "w") ftp.cwd("OUT") gettext(ftp, filename, outfile) ftp.quit() if __name__ == "__main__": main() </code> The script actually runs fine when "ftp.ftpserver.com" == "my_server_a", however when "ftp.ftpserver.com" == "my_server_b", it produces: <snip> Traceback (most recent call last): File "/usr/local/bin/get_afendis_STATS_from_ftp.py", line 24, in ? main() File "/usr/local/bin/get_afendis_STATS_from_ftp.py", line 20, in main gettext(ftp, filename, outfile) File "/usr/local/bin/get_afendis_STATS_from_ftp.py", line 7, in gettext ftp.retrlines("RETR %s" % filename, lambda s, w=outfile.write: w(s +"\n")) File "/usr/lib/python2.4/ftplib.py", line 396, in retrlines conn = self.transfercmd(cmd) File "/usr/lib/python2.4/ftplib.py", line 345, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/usr/lib/python2.4/ftplib.py", line 324, in ntransfercmd conn.connect(sa) File "<string>", line 1, in connect socket.error: (110, 'Connection timed out') </snip> So it looks like "my_server_b" has some different requirements or something? I don't have much experience with the ftp-protocol, so I thought maybe you guys could point me in the right direction? The files are definitely existent on the servers, and when I connect to them via the shell, I can up- and download files as I want. Seems like the call to ftp.retrlines() somehow doesn't work... I'm also not sure about ftp.set_pasv(1). Regards, Paul From tetsuo2k6 at web.de Tue Aug 19 16:06:28 2008 From: tetsuo2k6 at web.de (Paul Schewietzek) Date: Tue, 19 Aug 2008 16:06:28 +0200 Subject: [Tutor] SOLVED: [ FTP question (slightly OT)] In-Reply-To: <1219151804.5451.23.camel@tetsuo.powmark.local> References: <1219151804.5451.23.camel@tetsuo.powmark.local> Message-ID: <1219154788.5451.28.camel@tetsuo.powmark.local> Just found the solution, I didn't realize that ftplib has 'passive mode' as the standard - so I ended up with never actually trying to use 'active mode'.... Thanks nonetheless :) Am Dienstag, den 19.08.2008, 15:16 +0200 schrieb Paul Schewietzek: > Hello everyone, > > > > I put together the following, most of it is from different howtos on the > web. > > <code> > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > def gettext(ftp, filename, outfile=None): > if outfile is None: > outfile = sys.stdout > ftp.retrlines("RETR %s" % filename, lambda s, w=outfile.write: > w(s+"\n")) > > def main(): > from ftplib import FTP > import datetime > ftp = FTP("ftp.ftpserver.com") > ftp.login("my_username", "my_passwd") > ftp.set_pasv(1) > > filename = "name_of_textfile" > outfile = open(filename, "w") > > ftp.cwd("OUT") > gettext(ftp, filename, outfile) > ftp.quit() > > if __name__ == "__main__": > main() > </code> > > The script actually runs fine when "ftp.ftpserver.com" == "my_server_a", > however when "ftp.ftpserver.com" == "my_server_b", it produces: > > <snip> > Traceback (most recent call last): > File "/usr/local/bin/get_afendis_STATS_from_ftp.py", line 24, in ? > main() > File "/usr/local/bin/get_afendis_STATS_from_ftp.py", line 20, in main > gettext(ftp, filename, outfile) > File "/usr/local/bin/get_afendis_STATS_from_ftp.py", line 7, in > gettext > ftp.retrlines("RETR %s" % filename, lambda s, w=outfile.write: w(s > +"\n")) > File "/usr/lib/python2.4/ftplib.py", line 396, in retrlines > conn = self.transfercmd(cmd) > File "/usr/lib/python2.4/ftplib.py", line 345, in transfercmd > return self.ntransfercmd(cmd, rest)[0] > File "/usr/lib/python2.4/ftplib.py", line 324, in ntransfercmd > conn.connect(sa) > File "<string>", line 1, in connect > socket.error: (110, 'Connection timed out') > </snip> > > So it looks like "my_server_b" has some different requirements or > something? I don't have much experience with the ftp-protocol, so I > thought maybe you guys could point me in the right direction? > > The files are definitely existent on the servers, and when I connect to > them via the shell, I can up- and download files as I want. > > Seems like the call to ftp.retrlines() somehow doesn't work... > > I'm also not sure about ftp.set_pasv(1). > > > > Regards, Paul > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lie.1296 at gmail.com Tue Aug 19 19:01:13 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 20 Aug 2008 00:01:13 +0700 Subject: [Tutor] how to read Messages sorted by thread in thunderbird In-Reply-To: <mailman.19114.1219139331.920.tutor@python.org> References: <mailman.19114.1219139331.920.tutor@python.org> Message-ID: <1219165273.13698.61.camel@lieryan-laptop> > > Message: 6 > Date: Tue, 19 Aug 2008 02:48:39 -0700 > From: "Timothy Grant" <timothy.grant at gmail.com> > Subject: Re: [Tutor] how to read Messages sorted by thread in > thunderbird > To: scsoce <scsoce at gmail.com> > Cc: tutor at python.org > Message-ID: > <e775286d0808190248g2fed543dj8a3f87ff857100a5 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > (snip irrelevant quotes) If you're subscribed from the digest, when replying, do not quote the whole digest, instead cut off the parts that is necessary and relevant to the current thread. If you're creating a new thread, usually you'd not quote at all. > Looks to me like you might be subscribed to the digest instead of > individual messages. If you're subscribed to the digest, you likely > have to read the messages in the order the digest provides them. I do not know about Thunderbird, but I am using Evolution, and although I am subscribed to the digest, I can get the "regular listing" on the thread I'm following by replying in this way: 1. Make sure the Subject line matches the thread (and add RE: if necessary) 2. In the To: Field, insert tutor at python.org 3. In the CC line, insert the email of original poster, and people who has followed the thread (usually in the To and CC field of the email you are replying to). Evolution (possibly Thunderbird too) would group related emails (although its detection is a bit weak and reserved). > -- > Stand Fast, > tjg. [Timothy Grant] > From Jaggojaggo+Py at gmail.com Tue Aug 19 21:12:20 2008 From: Jaggojaggo+Py at gmail.com (OmerT) Date: Tue, 19 Aug 2008 22:12:20 +0300 Subject: [Tutor] how to read Messages sorted by thread in thunderbird In-Reply-To: <1219165273.13698.61.camel@lieryan-laptop> References: <mailman.19114.1219139331.920.tutor@python.org> <1219165273.13698.61.camel@lieryan-laptop> Message-ID: <515008f10808191212p13137e31p1e13397305bedfcb@mail.gmail.com> Using gmail and messages are sorted into threads by subject automatically. (I did have to switch back from digest to regular mode..) HTH. On Tue, Aug 19, 2008 at 8:01 PM, Lie Ryan <lie.1296 at gmail.com> wrote: > >> >> Message: 6 >> Date: Tue, 19 Aug 2008 02:48:39 -0700 >> From: "Timothy Grant" <timothy.grant at gmail.com> >> Subject: Re: [Tutor] how to read Messages sorted by thread in >> thunderbird >> To: scsoce <scsoce at gmail.com> >> Cc: tutor at python.org >> Message-ID: >> <e775286d0808190248g2fed543dj8a3f87ff857100a5 at mail.gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1 >> > > (snip irrelevant quotes) > If you're subscribed from the digest, when replying, do not quote the > whole digest, instead cut off the parts that is necessary and relevant > to the current thread. If you're creating a new thread, usually you'd > not quote at all. > >> Looks to me like you might be subscribed to the digest instead of >> individual messages. If you're subscribed to the digest, you likely >> have to read the messages in the order the digest provides them. > > I do not know about Thunderbird, but I am using Evolution, and although > I am subscribed to the digest, I can get the "regular listing" on the > thread I'm following by replying in this way: > 1. Make sure the Subject line matches the thread (and add RE: if > necessary) > 2. In the To: Field, insert tutor at python.org > 3. In the CC line, insert the email of original poster, and people who > has followed the thread (usually in the To and CC field of the email you > are replying to). > > Evolution (possibly Thunderbird too) would group related emails > (although its detection is a bit weak and reserved). > >> -- >> Stand Fast, >> tjg. [Timothy Grant] >> > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Tue Aug 19 21:50:02 2008 From: emile at fenx.com (Emile van Sebille) Date: Tue, 19 Aug 2008 12:50:02 -0700 Subject: [Tutor] help with sorted() In-Reply-To: <20080817155041.GR2609@niof.net> References: <20080817155041.GR2609@niof.net> Message-ID: <g8f85h$8e6$1@ger.gmane.org> Rick Pasotto wrote: > I have a dictionary that looks like: d = {k:[v1,[v2,v3,v4]]} > > v1,v2,v3,v4 are integers. > > I want to print the dictionary sorted by v1, high to low. > > sorted(d,operator.itemgetter(0),reverse=True) You need to pass a compare function in... try for ii in sorted(d,lambda ii,jj: cmp(d[jj][0],d[ii][0])): d[ii] HTH, Emile > > gives me the keys in some order different than if I just looped through > the dictionary and not in key order but also not in any order that I can > see. It really appears random. > > sorted(d) does give me a sorted list of keys. > > How do I sort on v1? How would I sort on v3? > From jmorcombe at westnet.com.au Wed Aug 20 11:30:37 2008 From: jmorcombe at westnet.com.au (Jim Morcombe) Date: Wed, 20 Aug 2008 17:30:37 +0800 Subject: [Tutor] names and variables Message-ID: <48ABE43D.1010305@westnet.com.au> I have an object called "myObject" with an attribute called "colour". If I type: print myObject.colour then python prints: red Now, I have a variable "myAttribute" and set its value to "colour" by typing: myAttribute = "colour" I want to have a line of code: something like this: print myObject.myAttribute and have Python interpret it as meaning "print myObject.colour" and hence print "red" Can this be done? If so, how? Jim Morcombe From marc.tompkins at gmail.com Wed Aug 20 11:37:23 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 20 Aug 2008 02:37:23 -0700 Subject: [Tutor] names and variables In-Reply-To: <48ABE43D.1010305@westnet.com.au> References: <48ABE43D.1010305@westnet.com.au> Message-ID: <40af687b0808200237ucfd6c4fy52cb8d671c2a10c5@mail.gmail.com> On Wed, Aug 20, 2008 at 2:30 AM, Jim Morcombe <jmorcombe at westnet.com.au>wrote: > I have an object called "myObject" with an attribute called "colour". > > If I type: > print myObject.colour > then python prints: > red > > Now, I have a variable "myAttribute" and set its value to "colour" by > typing: > myAttribute = "colour" > > I want to have a line of code: something like this: > print myObject.myAttribute > and have Python interpret it as meaning "print myObject.colour" and hence > print "red" > > > Can this be done? If so, how? > > Jim Morcombe > print(getattr(myObject, "colour")) Here's the effbot article: http://effbot.org/zone/python-getattr.htm -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080820/95e4d717/attachment-0001.htm> From lie.1296 at gmail.com Wed Aug 20 12:54:39 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 20 Aug 2008 17:54:39 +0700 Subject: [Tutor] names and variables In-Reply-To: <mailman.19946.1219225053.920.tutor@python.org> References: <mailman.19946.1219225053.920.tutor@python.org> Message-ID: <1219229679.6388.32.camel@lieryan-laptop> On Wed, 2008-08-20 at 11:37 +0200, tutor-request at python.org wrote: > Message: 7 > Date: Wed, 20 Aug 2008 17:30:37 +0800 > From: Jim Morcombe <jmorcombe at westnet.com.au> > Subject: [Tutor] names and variables > To: tutor at python.org > Message-ID: <48ABE43D.1010305 at westnet.com.au> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > I have an object called "myObject" with an attribute called "colour". > > If I type: > print myObject.colour > then python prints: > red > > Now, I have a variable "myAttribute" and set its value to "colour" by > typing: > myAttribute = "colour" > > I want to have a line of code: something like this: > print myObject.myAttribute > and have Python interpret it as meaning "print myObject.colour" and > hence print "red" > > > Can this be done? If so, how? > Do you mean this: >>> class A(object): pass ... >>> class A(object): ... colour = 'red' ... >>> a = A() >>> def getcolour(self): ... print self.colour >>> A.myAttribute = getcolour >>> a.myAttribute() 'red' Of course, this is why python's is called dynamic language: the ability to change a class' definition on runtime, even on an already instantiated objects. From kent37 at tds.net Wed Aug 20 14:19:15 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Aug 2008 08:19:15 -0400 Subject: [Tutor] names and variables In-Reply-To: <40af687b0808200237ucfd6c4fy52cb8d671c2a10c5@mail.gmail.com> References: <48ABE43D.1010305@westnet.com.au> <40af687b0808200237ucfd6c4fy52cb8d671c2a10c5@mail.gmail.com> Message-ID: <1c2a2c590808200519x7f25c454g3cf048642afed341@mail.gmail.com> On Wed, Aug 20, 2008 at 5:37 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote: > print(getattr(myObject, "colour")) Or, of course, print getattr(myObject, myAttribute) which is what the OP wanted. Kent From jeff at drinktomi.com Wed Aug 20 20:29:41 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 20 Aug 2008 11:29:41 -0700 Subject: [Tutor] Is this a "Class" problem? In-Reply-To: <866c750d0808200711y3afd8778y57b00a9f85079447@mail.gmail.com> References: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> <866c750d0808200711y3afd8778y57b00a9f85079447@mail.gmail.com> Message-ID: <56D4173D-A7E1-4577-BD29-E74AB83081EB@drinktomi.com> > I'm assuming you do that so that you don't confuse what a Python > built-in method (or function) is, > compared to methods (or functions) that you've authored. It's done more to distinguish classes from methods and attributes. I can't claim any credit though. It's part of the python coding conventions in PEP-8. You can find the document at http://www.python.org/dev/peps/pep-0008 . The actual coding convention for attribute and variable names is lower_case_separated_by_underscores, but there are projects out there that use initialLowerCamelCase. Pick whatever your current project is using and stick with it. -jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080820/d2570649/attachment.htm> From dave6502 at googlemail.com Wed Aug 20 21:54:19 2008 From: dave6502 at googlemail.com (dave selby) Date: Wed, 20 Aug 2008 20:54:19 +0100 Subject: [Tutor] named pipe problem Message-ID: <f52017b60808201254t64fb6147t81dfa5c1b025080e@mail.gmail.com> Hi All, I am trying to get a named pipe working, I have already made a fifo dave at dev-system:/usr/local/bin$ ls -al /home/dave/kmotion2/www/pipe_func prw-rw---- 1 dave www-data 0 2008-08-20 20:25 /home/dave/kmotion2/www/pipe_func dave at dev-system:/usr/local/bin$ but when I execute my test code to add an item to the fifo ... func = '199' www_dir = '/home/dave/kmotion2/www' print '%s/pipe_func' % www_dir pipeout = os.open('%s/pipe_func' % www_dir, os.O_WRONLY) print 'xxx' os.write(pipeout, func) os.close(pipeout) I get the path printed out & then the script hangs silently on pipeout = os.open('%s/pipe_func' % www_dir, os.O_WRONLY) Can anyone tell me why ? I expected it to return immediately Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From dotancohen at gmail.com Wed Aug 20 22:43:32 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 20 Aug 2008 23:43:32 +0300 Subject: [Tutor] Reformatting phone number Message-ID: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> I have a small script (linux) that takes a phone number as an argument: #!/usr/bin/env python import sys number = '+' + sys.argv[1] .... However, if the first digit of the phone number is a 0 then I need to replace that 0 with "972". I can add the "972", but how do I remove the leading "0"? For instance, this code: #!/usr/bin/env python import sys if sys.argv[1][0] == 0: number = '+972' + sys.argv[1] else: number = '+' + sys.argv[1] Turns the phone number "0123" into "9720123" but I need "972123". How is this done? Better yet, where in the fine manual would I find this? Thanks in advance. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From dotancohen at gmail.com Wed Aug 20 22:50:55 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 20 Aug 2008 23:50:55 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> Message-ID: <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> I have gotten a bit farther, but I cannot get this to work as described in the previous mail: #!/usr/bin/env python import sys preNumber = sys.argv[1] if preNumber[0] == 0: number = '+972' + preNumber[1:] else: number = '+' + preNumber Where is my flaw? -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From kent37 at tds.net Wed Aug 20 22:53:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Aug 2008 16:53:51 -0400 Subject: [Tutor] named pipe problem In-Reply-To: <f52017b60808201254t64fb6147t81dfa5c1b025080e@mail.gmail.com> References: <f52017b60808201254t64fb6147t81dfa5c1b025080e@mail.gmail.com> Message-ID: <1c2a2c590808201353y60fa3c65t8a2cf6a62707d5d3@mail.gmail.com> On Wed, Aug 20, 2008 at 3:54 PM, dave selby <dave6502 at googlemail.com> wrote: > Hi All, > > > I am trying to get a named pipe working, I have already made a fifo > > dave at dev-system:/usr/local/bin$ ls -al /home/dave/kmotion2/www/pipe_func > prw-rw---- 1 dave www-data 0 2008-08-20 20:25 /home/dave/kmotion2/www/pipe_func > dave at dev-system:/usr/local/bin$ > > but when I execute my test code to add an item to the fifo ... > > func = '199' > www_dir = '/home/dave/kmotion2/www' > print '%s/pipe_func' % www_dir > pipeout = os.open('%s/pipe_func' % www_dir, os.O_WRONLY) > print 'xxx' > os.write(pipeout, func) > os.close(pipeout) > > I get the path printed out & then the script hangs silently on pipeout > = os.open('%s/pipe_func' % www_dir, os.O_WRONLY) > > Can anyone tell me why ? I expected it to return immediately See this informative thread: http://mail.python.org/pipermail/python-list/2006-August/396499.html Summary: opening a pipe for write blocks until it is also opened for read. Kent From dotancohen at gmail.com Wed Aug 20 22:58:28 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Wed, 20 Aug 2008 23:58:28 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> Message-ID: <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> I was missing the quotes in the if statement. Changing if preNumber[0] == 0: to if preNumber[0] == "0": fixed the problem. Why did I need those quotes? The 0 is numerical, so it should not need the quotes, no? -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From bermanrl at embarqmail.com Wed Aug 20 23:05:46 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Wed, 20 Aug 2008 17:05:46 -0400 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> Message-ID: <48AC872A.8000209@embarqmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080820/c15f2489/attachment-0001.htm> From kent37 at tds.net Wed Aug 20 23:07:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Aug 2008 17:07:19 -0400 Subject: [Tutor] named pipe problem In-Reply-To: <1c2a2c590808201353y60fa3c65t8a2cf6a62707d5d3@mail.gmail.com> References: <f52017b60808201254t64fb6147t81dfa5c1b025080e@mail.gmail.com> <1c2a2c590808201353y60fa3c65t8a2cf6a62707d5d3@mail.gmail.com> Message-ID: <1c2a2c590808201407r669328eaocd86319835ad458f@mail.gmail.com> On Wed, Aug 20, 2008 at 4:53 PM, Kent Johnson <kent37 at tds.net> wrote: > See this informative thread: > http://mail.python.org/pipermail/python-list/2006-August/396499.html > > Summary: opening a pipe for write blocks until it is also opened for read. Also, on Mac OSX at least ordinary file operations seem to work fine. For example, in one Terminal window: $ mkfifo testf $ cat < testf In another Terminal window, start Python and type In [5]: f=open('testf', 'w') In [6]: f.write('foo\n') In [7]: f.flush() In [8]: f.close() The output appears in the first window and the cat command finishes. If do the Python part first, the open() blocks until I issue the cat command. Kent From dotancohen at gmail.com Wed Aug 20 23:27:30 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 00:27:30 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <48AC872A.8000209@embarqmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> <48AC872A.8000209@embarqmail.com> Message-ID: <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> 2008/8/21 Robert Berman <bermanrl at embarqmail.com>: > Perhaps because preNumber is a character and not an integer? > Perhaps. In php the distinction was made by the fact that there were no non-numerical characters in a string. I don't know enough Python to know if this is the case. Can I declare a variable type in Python as in C? -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From bermanrl at embarqmail.com Thu Aug 21 00:08:47 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Wed, 20 Aug 2008 18:08:47 -0400 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> <48AC872A.8000209@embarqmail.com> <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> Message-ID: <48AC95EF.80200@embarqmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080820/eb6bed8a/attachment.htm> From alan.gauld at btinternet.com Thu Aug 21 00:29:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 20 Aug 2008 23:29:45 +0100 Subject: [Tutor] Reformatting phone number References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com><880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com><880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com><48AC872A.8000209@embarqmail.com> <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> Message-ID: <g8i5st$t8h$1@ger.gmane.org> "Dotan Cohen" <dotancohen at gmail.com> wrote > know if this is the case. Can I declare a variable type in Python as > in C? In Python values have types and variables are simply names associated with values. Thus v = '123' # v 'is' a string because '123' is a string v = 123 # now v 'is' an int because 123 is an int. The variable takes on the type of the value with which it is associated but it can be made to refer to any other value and thus its type effectively changes. So it's best not to think of variables having types but rather consider objects (or values) as having a type, and variables as being associated with objects.. This is one of the most fundamental characteristics of Python and one of the hardest for users of other languages to adapt to. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dotancohen at gmail.com Thu Aug 21 00:38:31 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 01:38:31 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <48AC95EF.80200@embarqmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> <48AC872A.8000209@embarqmail.com> <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> <48AC95EF.80200@embarqmail.com> Message-ID: <880dece00808201538t3bdf92e5ofc7cf84228d36ce9@mail.gmail.com> 2008/8/21 Robert Berman <bermanrl at embarqmail.com>: > Not directly as in C, but, for example, if you have s='3' and you want s > used as an integer, you can say s=int(s) and it is an integer. Conversely, > if you have a question about the type, you could also say type(s) which, > depending, will return, 'str','int', etc. > > Hope this helps a bit. > It does help, and I will make a point of familiarizing myself with the errors reported by runtime errors (is this a valid term in Python, as there are no compile errors) such as those generated from code like this: s='hello, world!' s=int(s) -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From dotancohen at gmail.com Thu Aug 21 00:39:47 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 01:39:47 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <g8i5st$t8h$1@ger.gmane.org> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> <48AC872A.8000209@embarqmail.com> <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> <g8i5st$t8h$1@ger.gmane.org> Message-ID: <880dece00808201539t3a3d392cl304190026572f9a5@mail.gmail.com> 2008/8/21 Alan Gauld <alan.gauld at btinternet.com>: > "Dotan Cohen" <dotancohen at gmail.com> wrote > >> know if this is the case. Can I declare a variable type in Python as >> in C? > > In Python values have types and variables are simply > names associated with values. > > Thus > > v = '123' # v 'is' a string because '123' is a string > v = 123 # now v 'is' an int because 123 is an int. > > The variable takes on the type of the value with which it is > associated but it can be made to refer to any other value > and thus its type effectively changes. So it's best not to > think of variables having types but rather consider objects > (or values) as having a type, and variables as being > associated with objects.. > > This is one of the most fundamental characteristics of > Python and one of the hardest for users of other languages > to adapt to. > This characteristic is similar enough to php (a language where one doesn't even think about types) that I will get used to it. Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From kent37 at tds.net Thu Aug 21 01:41:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Aug 2008 19:41:26 -0400 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> Message-ID: <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> On Wed, Aug 20, 2008 at 4:43 PM, Dotan Cohen <dotancohen at gmail.com> wrote: > I have a small script (linux) that takes a phone number as an argument: > #!/usr/bin/env python > import sys > number = '+' + sys.argv[1] > .... > > However, if the first digit of the phone number is a 0 then I need to > replace that 0 with "972". I can add the "972", but how do I remove > the leading "0"? > > For instance, this code: > #!/usr/bin/env python > import sys > if sys.argv[1][0] == 0: Another way to write this is if sys.argv[1].startswith('0'): > number = '+972' + sys.argv[1] You need to learn about slicing. This is a way of indexing any sequence, including strings. See http://docs.python.org/tut/node5.html#SECTION005120000000000000000 http://docs.python.org/lib/typesseq.html In particular, you want number = '+972' + sys.argv[1][1:] which takes all characters of argv[0] after the first. Kent From cloudneozero at gmail.com Thu Aug 21 02:30:32 2008 From: cloudneozero at gmail.com (Ark) Date: Wed, 20 Aug 2008 19:30:32 -0500 Subject: [Tutor] programming tic tac toe Message-ID: <9dd22c9c0808201730x50050222qc7354b833d9f91f0@mail.gmail.com> Hi. I programmed a simple tic tac toe game in python. I already finished it, but I'm not pleased with the way I used to identify a line. I used a list (with lists inside) to represent the board. And to identify a winning line I used many if's, like this one: def line(board): if board[0][0] == board[1][1] == board[2][2]: return True ... ... return False It's only an examble, but I did it that way. I did not like using all those if's, and I would like to hear suggestions to find a line in the board, maybe a more intelligent approach. I would like a solution using lists because it would be useful for example in C too, but I have been thinking about another way to represent a board. Ark -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080820/60470fc1/attachment-0001.htm> From alan.gauld at btinternet.com Thu Aug 21 07:53:50 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Aug 2008 06:53:50 +0100 Subject: [Tutor] programming tic tac toe References: <9dd22c9c0808201730x50050222qc7354b833d9f91f0@mail.gmail.com> Message-ID: <g8ivti$rj6$1@ger.gmane.org> "Ark" <cloudneozero at gmail.com> wrote > I used a list (with lists inside) to represent the board. And to > identify a > winning line I used many if's, like this one: > def line(board): > if board[0][0] == board[1][1] == board[2][2]: > return True > I did not like using all those if's, and I would like to hear > suggestions to > find a line in the board, maybe a more intelligent approach. Given that there are always 3x3 cells on an oxo board and therefore only 8 possible winning lines hard coding is probably a reasonable approach. You could make it into a single boolean condition which would be slightly less typing and slightly faster but otherwise what you have is fine I think: def line(board): return board[0][0] == board[0][1] == board[0][2] or board[1][0] == board[1][1] == board[1][2] or ... board[2][0] == board[1][1] == board[[0][2] But I'm not sure its that much nicer! :-) For the more general case of an NxN board then you should probably consider using a loop and relative indexing but for 3x3 hard coded is better IMHO. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dotancohen at gmail.com Thu Aug 21 08:08:07 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 09:08:07 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> Message-ID: <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> 2008/8/21 Kent Johnson <kent37 at tds.net>: > Another way to write this is > if sys.argv[1].startswith('0'): Nice! I had looked for this type of function, but could not find it. Is there a list of functions, organized by categories, for Python? Take for example these pages from te php documentation: http://il.php.net/manual/en/book.strings.php http://il.php.net/manual/en/book.array.php http://il.php.net/manual/en/book.math.php which are all linked from: http://il.php.net/manual/en/funcref.php Is there anything like this for Python? If not, I am willing to code the site if some Python gurus will help contribute their knowledge. > You need to learn about slicing. This is a way of indexing any > sequence, including strings. See > http://docs.python.org/tut/node5.html#SECTION005120000000000000000 This I have read, while googling this thread. > http://docs.python.org/lib/typesseq.html This I will read, to keep up to speed. Thanks! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From dotancohen at gmail.com Thu Aug 21 08:13:21 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 09:13:21 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <48ACB95B.4060905@embarqmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <880dece00808201350m2410bfaar36167195408b8142@mail.gmail.com> <880dece00808201358x25a1ad9bmc4a39e3ffb5faff@mail.gmail.com> <48AC872A.8000209@embarqmail.com> <880dece00808201427p47d5fe9ne54cb3c0f4a375ab@mail.gmail.com> <48AC95EF.80200@embarqmail.com> <880dece00808201538t3bdf92e5ofc7cf84228d36ce9@mail.gmail.com> <48ACB95B.4060905@embarqmail.com> Message-ID: <880dece00808202313h236edea3l33245d6fcec2c80b@mail.gmail.com> 2008/8/21 Robert Berman <bermanrl at embarqmail.com>: > One can 'quasi' compile Python code. Since you come from a C background and > I come from a C++ background, a Python compile isn't really compiling an > object module. I don't see an object file, I don't see an executable; > therefore, in my opinion, Python is an interpretive language and I love it. > It is easy to work with. It is incredibly friendly, incredibly powerful, and > it makes building algorithms and shells not only easy but also fun. I really > like this language. The more I learn of it, the more I like it. True, at > times I do miss the speed of C and C++; but I think we tend to ignore the > cost of development time excesses in those languages. I don't have more of a C background than a one-semester course in university. But the details between the languages are night and day. I am enjoying Python. I recently heard that Python is like writing psuedo-code that runs. I am seeing that this is true. I especially love the use of indentation for block demarcation. > To answer your question, I hope. You get errors from the interpretor and > from Python at run time. The interpretor errors tend to be very easy to spot > and to fix; they are primarily indentation or syntax errors. The run time > errors actually show you what failed. You can experiment until you fix them. Error are certainly the best way to learn. > I hope you enjoy using the language as much as I do. Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From Jaggojaggo+Py at gmail.com Thu Aug 21 09:32:14 2008 From: Jaggojaggo+Py at gmail.com (OmerT) Date: Thu, 21 Aug 2008 10:32:14 +0300 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> Message-ID: <515008f10808210032j65ae3144pc06275954ce0e996@mail.gmail.com> mostly, I google "docs.python" and the term or class I'm looking for. Mind, this mainly works for modules or classes which came with the interpreter. G'luck. On Thu, Aug 21, 2008 at 9:08 AM, Dotan Cohen <dotancohen at gmail.com> wrote: > 2008/8/21 Kent Johnson <kent37 at tds.net>: >> Another way to write this is >> if sys.argv[1].startswith('0'): > > Nice! I had looked for this type of function, but could not find it. > > Is there a list of functions, organized by categories, for Python? > Take for example these pages from te php documentation: > http://il.php.net/manual/en/book.strings.php > http://il.php.net/manual/en/book.array.php > http://il.php.net/manual/en/book.math.php > > which are all linked from: > http://il.php.net/manual/en/funcref.php > > Is there anything like this for Python? If not, I am willing to code > the site if some Python gurus will help contribute their knowledge. > > > >> You need to learn about slicing. This is a way of indexing any >> sequence, including strings. See >> http://docs.python.org/tut/node5.html#SECTION005120000000000000000 > > This I have read, while googling this thread. > >> http://docs.python.org/lib/typesseq.html > > This I will read, to keep up to speed. > > Thanks! > > -- > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > ?-?-?-?-?-?-? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Thu Aug 21 10:03:50 2008 From: emile at fenx.com (Emile van Sebille) Date: Thu, 21 Aug 2008 01:03:50 -0700 Subject: [Tutor] programming tic tac toe In-Reply-To: <9dd22c9c0808201730x50050222qc7354b833d9f91f0@mail.gmail.com> References: <9dd22c9c0808201730x50050222qc7354b833d9f91f0@mail.gmail.com> Message-ID: <g8j7hf$hu3$1@ger.gmane.org> Ark wrote: > Hi. > I programmed a simple tic tac toe game in python. I already finished > it, but I'm not pleased with the way I used to identify a line. > I used a list (with lists inside) to represent the board. And to > identify a winning line I used many if's, like this one: > def line(board): > if board[0][0] == board[1][1] == board[2][2]: > return True > ... > ... > return False #Assuming you number the board positions as: #board = [ [0,1,2], # [3,4,5], # [6,7,8] ] #then you could define the winning combinations as: winners = [ (0,1,2),(3,4,5),(6,7,8), #rows (0,3,6),(1,4,7),(2,5,8), #cols (0,4,8),(6,4,2) #diags ] #and return all these combinations from the current board with: def mapped(board): return [ (board[i/3][i%3],board[j/3][j%3],board[k/3][k%3]) for i,j,k in winners] #and finally, assuming you're using X's and Y's, #identify a winning line with: def line(board): if ( ('X','X','X') in mapped(board) or ('Y','Y','Y') in mapped(board) ): return True return False #now two test cases board = ([['X','Y','Y'], ['Y','X','X'], ['Y','X','Y'] ]) print line(board) board = ([['X','Y','Y'], ['Y','X','X'], ['Y','Y','X'] ]) print line(board) HTH, Emile > It's only an examble, but I did it that way. > I did not like using all those if's, and I would like to hear > suggestions to find a line in the board, maybe a more intelligent approach. > I would like a solution using lists because it would be useful for > example in C too, but I have been thinking about another way to > represent a board. > > Ark > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From think_fishbone at yahoo.com Thu Aug 21 11:56:49 2008 From: think_fishbone at yahoo.com (Kat) Date: Thu, 21 Aug 2008 02:56:49 -0700 (PDT) Subject: [Tutor] Merging table-like files with overlapping values in one column Message-ID: <691802.11223.qm@web45106.mail.sp1.yahoo.com> Hi all, I'm new to Python and trying to come up with an elegant way of tackling the following problem. Sorry for the lengthy description: I have several input files where in each file, every line has a space-separated pair values. The files are essentially tables with two columns. There are no duplicates in the first column values within each file, but they overlap when all files are considered. I'd like to merge them into one file according to values of the first column of each file with values from the second column of all files combined like this: First file: bar 100 foo 90 yadda 22 Second file: bar 78 yadda 120 ziggy 99 Combined file: bar 100 78 foo 90 NONE yadda 22 120 ziggy NONE 99 I'm considering several approaches. In the first brute force way, I can read in each file, parse it into lines, parse lines into words, and write the values from the second word to a new output file along with the first word. That seems awful. My second idea is to convert each file into a dictionary (since the first column's values are unique within each file), then I can create a combined dictionary which allows multiple values to each key, then output that. Does that sound reasonable? Is there another approach? I'm not asking for implementation of course, just ideas for the design. Thanks in advance. Kat From kent37 at tds.net Thu Aug 21 12:42:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Aug 2008 06:42:31 -0400 Subject: [Tutor] Merging table-like files with overlapping values in one column In-Reply-To: <691802.11223.qm@web45106.mail.sp1.yahoo.com> References: <691802.11223.qm@web45106.mail.sp1.yahoo.com> Message-ID: <1c2a2c590808210342p3813669paf8edc8a834a4502@mail.gmail.com> On Thu, Aug 21, 2008 at 5:56 AM, Kat <think_fishbone at yahoo.com> wrote: > I have several input files where in each file, every line has a space-separated pair values. The files are essentially tables with two columns. There are no duplicates in the first column values within each file, but they overlap when all files are considered. I'd like to merge them into one file according to values of the first column of each file with values from the second column of all files combined > > My second idea is to convert each file into a dictionary (since the first column's values are unique within each file), then I can create a combined dictionary which allows multiple values to each key, then output that. Does that sound reasonable? Yes, as long as the order of entries doesn't matter - a dict does not preserve order. Make a dict that maps a key to a list of values (collections.defaultdict is useful for this). Read each file and add its pairs to the dict. Then iterate the dict and write to a new file. If you do care about order, there are various implementations of ordered dictionaries available. Kent From kent37 at tds.net Thu Aug 21 12:50:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Aug 2008 06:50:10 -0400 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> Message-ID: <1c2a2c590808210350j2f1ee0a1pc10398d371f835cf@mail.gmail.com> On Thu, Aug 21, 2008 at 2:08 AM, Dotan Cohen <dotancohen at gmail.com> wrote: > Is there a list of functions, organized by categories, for Python? > Take for example these pages from te php documentation: > http://il.php.net/manual/en/book.strings.php > http://il.php.net/manual/en/book.array.php > http://il.php.net/manual/en/book.math.php Chapters 2 and 3 of the library reference are highly recommended. http://docs.python.org/lib/lib.html In particular: 2.1 Built-in Functions lists all globally available functions (functions that are not part of a class) 3.6 Sequence Types gives operations on strings, lists and tuples (which are all sequences) 3.6.1 String Methods includes endswith() 3.8 Mapping Types -- dict etc. Many Python functions are grouped into library modules. You could consider this to be the grouping by category that you want. The rest of the library reference (after chapter 3) documents the modules. Browse the table of contents to see what is available. And you are welcome to ask this group if you can't find what you are looking for. Kent From dotancohen at gmail.com Thu Aug 21 12:13:58 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 12:13:58 +0200 Subject: [Tutor] Reformatting phone number In-Reply-To: <515008f10808210032j65ae3144pc06275954ce0e996@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> <515008f10808210032j65ae3144pc06275954ce0e996@mail.gmail.com> Message-ID: <880dece00808210313w20ef5063ia0ff0cdbd269f286@mail.gmail.com> 2008/8/21 OmerT <Jaggojaggo+Py at gmail.com>: > mostly, I google "docs.python" and the term or class I'm looking for. > Mind, this mainly works for modules or classes which came with the interpreter. > Exactly- that only works for term, classes, and functions that you already know the name of. The php docs have a list of all the functions with a one-line description. It's very easy to find which funtion performs what one needs. I would have never found the startswith() function with the current document structure. But I suppose that is subject for another thread, which I am sure would degrade quickly into a flamewar. I don't want to be the cause of that :) -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From srilyk at gmail.com Thu Aug 21 13:31:09 2008 From: srilyk at gmail.com (W W) Date: Thu, 21 Aug 2008 06:31:09 -0500 Subject: [Tutor] Reformatting phone number In-Reply-To: <880dece00808210313w20ef5063ia0ff0cdbd269f286@mail.gmail.com> References: <880dece00808201343y94b6554v1d141193b9f422db@mail.gmail.com> <1c2a2c590808201641i5659c1c1ifb807d08de0d8815@mail.gmail.com> <880dece00808202308l25c06658y52504b6302a07254@mail.gmail.com> <515008f10808210032j65ae3144pc06275954ce0e996@mail.gmail.com> <880dece00808210313w20ef5063ia0ff0cdbd269f286@mail.gmail.com> Message-ID: <333efb450808210431v2f7355b9y332b126441fa9209@mail.gmail.com> On Thu, Aug 21, 2008 at 5:13 AM, Dotan Cohen <dotancohen at gmail.com> wrote: > 2008/8/21 OmerT <Jaggojaggo+Py at gmail.com <Jaggojaggo%2BPy at gmail.com>>: > > mostly, I google "docs.python" and the term or class I'm looking for. > > Mind, this mainly works for modules or classes which came with the > interpreter. > > > > Exactly- that only works for term, classes, and functions that you > already know the name of. The php docs have a list of all the > functions with a one-line description. It's very easy to find which > funtion performs what one needs. http://docs.python.org/modindex.html http://docs.python.org/lib/lib.html They may not have a one line description, but for the most part they're either fairly self explanatory or sounds like what they should. And if you still can't find what you want, just ask here, and someone should have an answer for you! HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080821/a8b3789a/attachment.htm> From dotancohen at gmail.com Thu Aug 21 18:01:46 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 19:01:46 +0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) Message-ID: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> 2008/8/21 Kent Johnson <kent37 at tds.net>: > Chapters 2 and 3 of the library reference are highly recommended. > http://docs.python.org/lib/lib.html Let's start from there. I need the startswith() function, but I do not know it's name. I search for "strings" and find this: 4. String Services * 4.1 string -- Common string operations o 4.1.3 String functions But on that page, this is all there is: """ The following functions are available to operate on string and Unicode objects. They are not available as string methods. capwords( s) [snip description] maketrans( from, to) [snip description] Warning: Don't use strings derived from lowercase and uppercase as arguments; in some locales, these don't have the same length. For case conversions, always use lower() and upper(). "" So Python has only two string functions? That's what it looks like. > In particular: > 2.1 Built-in Functions lists all globally available functions > (functions that are not part of a class) > 3.6 Sequence Types gives operations on strings, lists and tuples > (which are all sequences) > 3.6.1 String Methods includes endswith() > 3.8 Mapping Types -- dict > etc. I will start with those, thanks. > Many Python functions are grouped into library modules. You could > consider this to be the grouping by category that you want. The rest > of the library reference (after chapter 3) documents the modules. > Browse the table of contents to see what is available. > > And you are welcome to ask this group if you can't find what you are > looking for. Thanks, Kent. I will be a nuisance! Is there any place to suggest improvements to the docs? I see on the python.org site it is suggested to email website bugs to the site admin. Does that go for the docs? I am not the one to improve them at this time, as I am unfamiliar with the language, but I could report usability issues such as that mentioned here. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From dotancohen at gmail.com Thu Aug 21 18:13:59 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 19:13:59 +0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) Message-ID: <880dece00808210913l1ba065c9xce26e9b7185acf81@mail.gmail.com> 2008/8/21 W W <srilyk at gmail.com>: > On Thu, Aug 21, 2008 at 5:13 AM, Dotan Cohen <dotancohen at gmail.com> wrote: >> >> 2008/8/21 OmerT <Jaggojaggo+Py at gmail.com>: >> > mostly, I google "docs.python" and the term or class I'm looking for. >> > Mind, this mainly works for modules or classes which came with the >> > interpreter. >> > >> >> Exactly- that only works for term, classes, and functions that you >> already know the name of. The php docs have a list of all the >> functions with a one-line description. It's very easy to find which >> funtion performs what one needs. > > > http://docs.python.org/modindex.html > http://docs.python.org/lib/lib.html > > They may not have a one line description, but for the most part they're > either fairly self explanatory or sounds like what they should. And if you > still can't find what you want, just ask here, and someone should have an > answer for you! Thanks. Searching for startswith(), assuming that I do not know the name of it, leads me to the same p -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From o.lenstra at gmail.com Thu Aug 21 18:27:13 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Thu, 21 Aug 2008 18:27:13 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> Message-ID: <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> Follow-up on this question. I tried something (Posted below) but it doesn't work. Here it is. <<<<< import wx import os, sys class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(300, 250), style = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)) panel = wx.Panel(self, -1) wx.Gauge(panel, -1, 50, (50, 30), (200, 20)) wx.Button(panel, 1, 'Scan!', (115, 90)) wx.Button(panel, 2, 'Logs', (115, 120)) wx.Button(panel, 3, 'Version', (115, 150)) wx.Button(panel, 4, 'Credits', (115, 180)) self.Bind(wx.EVT_BUTTON, self.onScan, id=1) ## self.Bind(wx.EVT_BUTTON, self.onLogs, id=2) ## self.Bind(wx.EVT_BUTTON, self.onVersion, id=3) ## self.Bind(wx.EVT_BUTTON, self.onCredits, id=4) def onScan(self, event): self.myfile = open('foo.txt') self.count = 0 self.setTimer(0.01, self.processLine) def processLine(self): line = self.myfile.readline() if line: processLine(line) self.count += 1 self.myGauge.setValue(count) self.setTimer(0.01, self.processLine) else: self.myGuage.setValue(0) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, 'Troubleshooting Olrik') frame.Show(True) frame.Center() return True def main(): app = MyApp(0) app.MainLoop() if __name__ == '__main__': main() >>>>> I'm not sure what I'm doing wrong. Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080821/f19fbb9b/attachment.htm> From kent37 at tds.net Thu Aug 21 18:58:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Aug 2008 12:58:55 -0400 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> Message-ID: <1c2a2c590808210958s6703c0a2i3b9beff4774dd830@mail.gmail.com> On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen <dotancohen at gmail.com> wrote: > 2008/8/21 Kent Johnson <kent37 at tds.net>: >> Chapters 2 and 3 of the library reference are highly recommended. >> http://docs.python.org/lib/lib.html > > Let's start from there. I need the startswith() function, but I do not > know it's name. I search for "strings" and find this: > 4. String Services > * 4.1 string -- Common string operations > o 4.1.3 String functions and somehow you missed # 3.6.1 String Methods # 3.6.2 String Formatting Operations which even should have come first in your search. > But on that page, this is all there is: <snip> But the *very next page*, called "Deprecated string functions", links to 3.6.1 which is what you want. > So Python has only two string functions? That's what it looks like. I think it looks like you are not trying very hard, or that you are letting your expectations color your search too much. > Is there any place to suggest > improvements to the docs? I see on the python.org site it is suggested > to email website bugs to the site admin. Does that go for the docs? At the bottom of every page in the docs it says, "See About this document... [link] for information on suggesting changes." Specific suggestions for improvement are more likely to be well received than complaints. I guess I am a little defensive here, I think the docs are pretty good. It's true that beginners don't realize that so much meat is in the library reference, I'm not sure how to make that more obvious. But your particular problems in finding endswith() in the LR I think come from you wearing PHP-colored blinders. Kent From dotancohen at gmail.com Thu Aug 21 19:25:29 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 20:25:29 +0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <1c2a2c590808210958s6703c0a2i3b9beff4774dd830@mail.gmail.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <1c2a2c590808210958s6703c0a2i3b9beff4774dd830@mail.gmail.com> Message-ID: <880dece00808211025j66ba8de5ta6c828e0bb033622@mail.gmail.com> 2008/8/21 Kent Johnson <kent37 at tds.net>: > On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen <dotancohen at gmail.com> wrote: >> 2008/8/21 Kent Johnson <kent37 at tds.net>: >>> Chapters 2 and 3 of the library reference are highly recommended. >>> http://docs.python.org/lib/lib.html >> >> Let's start from there. I need the startswith() function, but I do not >> know it's name. I search for "strings" and find this: >> 4. String Services >> * 4.1 string -- Common string operations >> o 4.1.3 String functions > > and somehow you missed > # 3.6.1 String Methods > # 3.6.2 String Formatting Operations > > which even should have come first in your search. I remember passing on String Formatting Operations, but String Methods went right past me! >> But on that page, this is all there is: > <snip> > > But the *very next page*, called "Deprecated string functions", links > to 3.6.1 which is what you want. I did not look at depreciated functions because I want to learn the language that is, not the language that was. Why would I learn a function that will likely be removed soon when I can learn the proper replacement function? >> So Python has only two string functions? That's what it looks like. > > I think it looks like you are not trying very hard, or that you are > letting your expectations color your search too much. I am trying moderately hard, and I am letting my expectations color my experience. That's how I bugtest KDE, *buntus, and Fedora, and that is how I approach any new project. I make 90% effort and I ask about the other 10%. >> Is there any place to suggest >> improvements to the docs? I see on the python.org site it is suggested >> to email website bugs to the site admin. Does that go for the docs? > > At the bottom of every page in the docs it says, "See About this > document... [link] for information on suggesting changes." I conveniently did not read the footer of the page I was on, instead I grepped 10 pages starting from the homepage! Naturally... > Specific > suggestions for improvement are more likely to be well received than > complaints. Naturally, so long as I know the information. I don't file 'this sucks' bugs. > I guess I am a little defensive here, I think the docs are pretty > good. That's fine. I know that many a flamewar had begun in a similar vein, and even I feel that I am treading over troll-laden bridges when I mention these issues. > It's true that beginners don't realize that so much meat is in > the library reference, I'm not sure how to make that more obvious. That's why I asked to whom to suggest. It's easier for beginners to say "this is what I tried" than for the experienced to try to think like a noob. > But > your particular problems in finding endswith() in the LR I think come > from you wearing PHP-colored blinders. That may be. I know that I will have to make an effort to acquaint myself with the Python docs. Part of that effort is forgetting what I already know. Thank you for your suggestions and your patience. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From lie.1296 at gmail.com Thu Aug 21 19:42:23 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 22 Aug 2008 00:42:23 +0700 Subject: [Tutor] programming tic tac toe In-Reply-To: <mailman.63.1219312815.8227.tutor@python.org> References: <mailman.63.1219312815.8227.tutor@python.org> Message-ID: <1219340544.6275.32.camel@lieryan-laptop> > Message: 1 > Date: Thu, 21 Aug 2008 06:53:50 +0100 > From: "Alan Gauld" <alan.gauld at btinternet.com> > Subject: Re: [Tutor] programming tic tac toe > To: tutor at python.org > Message-ID: <g8ivti$rj6$1 at ger.gmane.org> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > "Ark" <cloudneozero at gmail.com> wrote > > > I used a list (with lists inside) to represent the board. And to > > identify a > > winning line I used many if's, like this one: > > def line(board): > > if board[0][0] == board[1][1] == board[2][2]: > > return True > > > I did not like using all those if's, and I would like to hear > > suggestions to > > find a line in the board, maybe a more intelligent approach. > > Given that there are always 3x3 cells on an oxo board and > therefore only 8 possible winning lines hard coding is probably > a reasonable approach. You could make it into a single boolean > condition which would be slightly less typing and slightly faster > but otherwise what you have is fine I think: > > def line(board): > return board[0][0] == board[0][1] == board[0][2] or > board[1][0] == board[1][1] == board[1][2] or > ... > board[2][0] == board[1][1] == board[[0][2] > > But I'm not sure its that much nicer! :-) > > For the more general case of an NxN board then you > should probably consider using a loop and relative > indexing but for 3x3 hard coded is better IMHO. For a generic NxM board, which wouldn't require any change of code for any board size, you might do something like this: The board class: Instead of using string as the representation of X and Y, you use +1 and -1 for X and O, and 0 for unfilled square. The check: For each rows and columns sum the line. If the sum equals to the width (for row) or height (for column), then we've got a winner (we've got a line that stretch from one end to another). Check the main diagonals' sum too. i.e.: [[0, 0, -1 ], [1, 0, -1], [1, 1, -1 ],] Sum for: Row 1: 0 + 0 + -1 = -1 Row 2: 1 + 0 + -1 = 0 Row 3: 1 + 1 + -1 = 1 Col 1: 0 + 1 + 1 = 2 Col 2: 0 + 0 + 1 = 1 Col 3: -1 + -1 + -1 = -3 # We've got a winner Diag 1: 0 + 0 + -1 = -1 Diag 2: 1 + 0 + -1 = 0 in code: (untested) class Board(object): ... def iter_row(self): for row in self.board: yield row def iter_col(self): for col_num in range(len(self.board[0])): ret = [] for row in self.board: ret.append(row[col_num]) return ret def diagonals(self): ret = [] for n in range(len(self.board)): ret.append(self.board[n][n]) yield ret ret = [] for n in range(len(self.board)): ret.append(self.board[-n - 1][-n - 1]) yield ret ... def check(self): for row in self.iter_row: if sum(row) >= 3: print 'Winner X' if sum(row) <= -3: print 'Winner O' for col in self.iter_col: if sum(col) >= 3: print 'Winner X' if sum(col) <= -3: print 'Winner O' for diag in self.diagonals: if sum(diag) >= 3: print 'Winner X' if sum(diag) <= -3: print 'Winner O' .... It wouldn't be hard to make it a bit more shorter, like using this for import itertools def check(self): for line in itertools.chain(self.iter_row, self.iter_col, self.diagonals): if sum(line) >= 3: print 'Winner X' if sum(line) <= -3: print 'Winner O' But personally, I think it'd be hard to read and understand. After all these talks, if your Tic Tac Toe's board size is hard coded, yes, it'd be much better just to use plain long if-elifs. From lie.1296 at gmail.com Thu Aug 21 19:43:53 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 22 Aug 2008 00:43:53 +0700 Subject: [Tutor] Tutor Digest, Vol 54, Issue 72 In-Reply-To: <mailman.20396.1219266360.920.tutor@python.org> References: <mailman.20396.1219266360.920.tutor@python.org> Message-ID: <1219340633.6275.35.camel@lieryan-laptop> On Wed, 2008-08-20 at 23:06 +0200, tutor-request at python.org wrote: > > Message: 6 > Date: Wed, 20 Aug 2008 23:50:55 +0300 > From: "Dotan Cohen" <dotancohen at gmail.com> > Subject: Re: [Tutor] Reformatting phone number > To: python-tutor. <tutor at python.org> > Message-ID: > <880dece00808201350m2410bfaar36167195408b8142 at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > I have gotten a bit farther, but I cannot get this to work as > described in the previous mail: > > #!/usr/bin/env python > import sys > preNumber = sys.argv[1] > if preNumber[0] == 0: Python is strictly typed (unlike some languages like Javascript), you cannot compare a string with a number although the string only contains numbers. sys.argv[...] is a list of strings so preNumber[0] is a string, while 0 is an integer. > number = '+972' + preNumber[1:] > else: > number = '+' + preNumber > > Where is my flaw? From bill at celestial.net Thu Aug 21 19:40:28 2008 From: bill at celestial.net (Bill Campbell) Date: Thu, 21 Aug 2008 10:40:28 -0700 Subject: [Tutor] Regular expression to match \f in groff input? Message-ID: <20080821174028.GA8040@ayn.mi.celestial.com> I've been beating my head against the wall try to figure out how to get regular expressions to match the font change sequences in *roff input (e.g. \fB for bold, \fP to revert to previous font). The re library maps r'\f' to the single form-feed character (as it does other common single-character sequences like r'\n'). In perl, I can write something like this: s/\f[1NR]/</emphasis>/g; This does not work in puthon: s = re.sub(r'\f[1NR]', '</emphasis>, sinput) The string.replace() operator will handle the above replacement, although it requires a separate replace for each of the possible characters in the [1NR]. I have tried various options such as r'\\x66' and r'\\146', but none of these work. One work-around, assuming that the text does not contain control characters, is to replace the \f characters with a control character before doing the replacements, then replace that control character with \f if any remain after processing: import re, fileinput for line in fileinput.input(): line = line.rstrip() line = line.replace(r'\f', r'\001') # do something here to make substitutions line = line.replace(r'\001', r'\f') print line 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 It is our duty still to endeavor to avoid war; but if it shall actually take place, no matter by whom brought on, we must defend ourselves. If our house be on fire, without inquiring whether it was fired from within or without, we must try to extinguish it. -- Thomas Jefferson to James Lewis, Jr., 1798. From dyoo at cs.wpi.edu Thu Aug 21 20:12:04 2008 From: dyoo at cs.wpi.edu (Danny Yoo) Date: Thu, 21 Aug 2008 14:12:04 -0400 Subject: [Tutor] Regular expression to match \f in groff input? In-Reply-To: <20080821174028.GA8040@ayn.mi.celestial.com> References: <20080821174028.GA8040@ayn.mi.celestial.com> Message-ID: <d06401780808211112s7e9e267fya35556c18ddff8ce@mail.gmail.com> On Thu, Aug 21, 2008 at 1:40 PM, Bill Campbell <bill at celestial.net> wrote: > I've been beating my head against the wall try to figure out how > to get regular expressions to match the font change sequences in > *roff input (e.g. \fB for bold, \fP to revert to previous font). > The re library maps r'\f' to the single form-feed character (as > it does other common single-character sequences like r'\n'). Does this example help? ########################################### >>> sampleText = r"\This\ has \backslashes\." >>> print sampleText \This\ has \backslashes\. >>> import re >>> re.findall(r"\\\w+\\", sampleText) ['\\This\\', '\\backslashes\\'] ########################################### From bgailer at gmail.com Thu Aug 21 20:17:10 2008 From: bgailer at gmail.com (bob gailer) Date: Thu, 21 Aug 2008 14:17:10 -0400 Subject: [Tutor] programming tic tac toe In-Reply-To: <9dd22c9c0808201730x50050222qc7354b833d9f91f0@mail.gmail.com> References: <9dd22c9c0808201730x50050222qc7354b833d9f91f0@mail.gmail.com> Message-ID: <48ADB126.7030402@gmail.com> Ark wrote: > Hi. > I programmed a simple tic tac toe game in python. I already finished > it, but I'm not pleased with the way I used to identify a line. > I used a list (with lists inside) to represent the board. And to > identify a winning line I used many if's, like this one: > def line(board): > if board[0][0] == board[1][1] == board[2][2]: > return True > ... > ... > return False > It's only an examble, but I did it that way. > I did not like using all those if's, and I would like to hear > suggestions to find a line in the board, maybe a more intelligent > approach. > I would like a solution using lists because it would be useful for > example in C too, but I have been thinking about another way to > represent a board. I tend to think in terms of classes and lists. So I wrote the following. A bit messy and complex, but easy to follow. # tic tac toe class Cell: player = None def __eq__(self, other): return self.player and other.player and self.player == other.player class Line: def __init__(self, *x): self.cells = [cells[y] for y in x] def winner(self): return self.cells[0] == self.cells[1] == self.cells[2] cells = [Cell() for row in range(9)] rows = [Line(0,3,6), Line(1,4,7), Line(2,5,8)] cols = [Line(0,1,2), Line(3,4,5), Line(6,7,8)] diags = [Line(0,4,8), Line(2,4,6)] lines = rows + cols + diags # in lieu of playing a game I just tested with a blank board and then with a row of X's for line in lines: if line.winner(): print "winner" break else: print "no winner" # Mark row 1 all X for cell in rows[1].cells: cell.player = 'X' for line in lines: if line.winner(): print "winner" bresk else: print "no winner" -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From alan.gauld at btinternet.com Thu Aug 21 20:26:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Aug 2008 19:26:53 +0100 Subject: [Tutor] Python Docs (Was: Reformatting phone number) References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> Message-ID: <g8kc1h$sia$1@ger.gmane.org> "Dotan Cohen" <dotancohen at gmail.com> wrote > Let's start from there. I need the startswith() function, but I do > not > know it's name. I search for "strings" and find this: > 4. String Services > * 4.1 string -- Common string operations > o 4.1.3 String functions Personally I rarely start with the documentation. I'd start either with the >>> prompt and the help() function or I may use dir() as in dir("") to get a list of all the attributes - including methods - of an object. If I don't undertand what dir/help tell me, or don't see anything promising, then I will search the docs. So here is my session looking for startwith... >>> help("") >>> dir("") ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__g t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__ ', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', ' __rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdi git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lst rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit' , 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', ' translate', 'upper', 'zfill'] >>> help("".startswith) Help on built-in function startswith: startswith(...) S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. If I'd done help(str) instead of help("") in the first case I'd have got the full help screen for string objects including startswith.. Never forget the >>> prompt as a source of research. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From malaclypse2 at gmail.com Thu Aug 21 20:29:26 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 21 Aug 2008 14:29:26 -0400 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> Message-ID: <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen <dotancohen at gmail.com> wrote: > 2008/8/21 Kent Johnson <kent37 at tds.net>: >> Chapters 2 and 3 of the library reference are highly recommended. >> http://docs.python.org/lib/lib.html > > Let's start from there. I need the startswith() function, but I do not > know it's name. I search for "strings" and find this: > 4. String Services > * 4.1 string -- Common string operations > o 4.1.3 String functions You went too far. Look at 3.6 (Sequence types) and 3.6.1 (String Methods). Those document operations that work on all types of sequences and the methods of the string type. That's 99% of what you'll need to know about python strings. Kent was pretty specific about looking at chapter two and three of the library reference. Why did you start with chapter four instead? > But on that page, this is all there is: > """ > The following functions are available to operate on string and Unicode > objects. They are not available as string methods. ... > So Python has only two string functions? That's what it looks like. There are only two (non-deprecated) functions in the string module. > > Thanks, Kent. I will be a nuisance! Is there any place to suggest > improvements to the docs? I see on the python.org site it is suggested > to email website bugs to the site admin. Does that go for the docs? I > am not the one to improve them at this time, as I am unfamiliar with > the language, but I could report usability issues such as that > mentioned here. I believe that doc bugs (and suggestions for improvements) are tracked on the python bug tracker (http://bugs.python.org/). If you're going to submit doc patches, you may want to take a look at http://docs.python.org/dev/3.0/ which I believe is the beta of the new documentation layout for python 3.0. I'm not sure how much the actual contents have changed from the 2.x docs though. I notice that the section on the string module does now refer you back to the methods of string and sequences in general, which the current docs do not. -- Jerry From alan.gauld at btinternet.com Thu Aug 21 20:32:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Aug 2008 19:32:48 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <542659.81506.qm@web86704.mail.ukl.yahoo.com><3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> Message-ID: <g8kccl$tsu$1@ger.gmane.org> "Olrik Lenstra" <o.lenstra at gmail.com> wrote > I tried something (Posted below) but it doesn't work. Closer but.... > class MyFrame(wx.Frame): > def __init__(self, parent, id, title): ... > panel = wx.Panel(self, -1) > > wx.Gauge(panel, -1, 50, (50, 30), (200, 20)) You need to store a referemce to the guage otherwise you cannot access it later self.myGauge = wx.Gauge(panel....) > def onScan(self, event): > self.myfile = open('foo.txt') > self.count = 0 > self.setTimer(0.01, self.processLine) > > def processLine(self): > line = self.myfile.readline() > if line: > processLine(line) This function needs to be defined somewhere obviously! It is a global function not a method of your class. > self.count += 1 > self.myGauge.setValue(count) And now you access the attribute you created in __init__ above... > self.setTimer(0.01, self.processLine) > else: > self.myGuage.setValue(0) Apart from not storing a reference to the gauge it was OK, or at least very close, I think. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 21 20:35:05 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Aug 2008 19:35:05 +0100 Subject: [Tutor] Regular expression to match \f in groff input? References: <20080821174028.GA8040@ayn.mi.celestial.com> Message-ID: <g8kcgt$ub6$1@ger.gmane.org> "Bill Campbell" <bill at celestial.net> wrote > to get regular expressions to match the font change sequences in > *roff input (e.g. \fB for bold, \fP to revert to previous font). > The re library maps r'\f' to the single form-feed character (as > it does other common single-character sequences like r'\n'). I think all you need is an extra \ to escape the \ character in \f > This does not work in puthon: > > s = re.sub(r'\f[1NR]', '</emphasis>, sinput) Try s = re.sub(r'\\f[1NR]', '</emphasis>, sinput) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Mike.Hansen at atmel.com Thu Aug 21 21:20:59 2008 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Thu, 21 Aug 2008 13:20:59 -0600 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D035B7056@csomb01.corp.atmel.com> > On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen > <dotancohen at gmail.com> wrote: > > 2008/8/21 Kent Johnson <kent37 at tds.net>: > >> Chapters 2 and 3 of the library reference are highly recommended. > >> http://docs.python.org/lib/lib.html > > > > Let's start from there. I need the startswith() function, > but I do not > > know it's name. I search for "strings" and find this: > > 4. String Services > > * 4.1 string -- Common string operations > > o 4.1.3 String functions > > You went too far. Look at 3.6 (Sequence types) and 3.6.1 (String > Methods). Those document operations that work on all types of > sequences and the methods of the string type. That's 99% of what > you'll need to know about python strings. Kent was pretty specific > about looking at chapter two and three of the library reference. Why > did you start with chapter four instead? > > > But on that page, this is all there is: > > """ > > The following functions are available to operate on string > and Unicode > > objects. They are not available as string methods. > ... > > So Python has only two string functions? That's what it looks like. > > There are only two (non-deprecated) functions in the string module. > > > > > Thanks, Kent. I will be a nuisance! Is there any place to suggest > > improvements to the docs? I see on the python.org site it > is suggested > > to email website bugs to the site admin. Does that go for > the docs? I > > am not the one to improve them at this time, as I am unfamiliar with > > the language, but I could report usability issues such as that > > mentioned here. > > I believe that doc bugs (and suggestions for improvements) are tracked > on the python bug tracker (http://bugs.python.org/). If you're going > to submit doc patches, you may want to take a look at > http://docs.python.org/dev/3.0/ which I believe is the beta of the new > documentation layout for python 3.0. I'm not sure how much the actual > contents have changed from the 2.x docs though. I notice that the > section on the string module does now refer you back to the methods of > string and sequences in general, which the current docs do not. > > -- > Jerry > _______________________________________________ I can't put my finger on it, but there's something lacking in the docs. They are not terrible, but they aren't fantastic either. I'm not entirely sure what I'd do to fix them. I usually rely on Learning Python, The Python Standard Library, the Global Module Index section of the docs, and sometimes Python in a Nutshell. I need to get in the habit of using help in the shell. Sometimes the docs for a particular module might be a little obtuse for me especially if it doesn't have example code. That's where The Python Standard Library book comes in handy since it has example code. After experimenting in the shell, if I really get stuck, I'll ask on this list. Maybe having tags or something to help with searches. On the string methods page, have a tag called "string functions". I don't think many new to the language are going to know that they are called "string methods" and not "string functions". I guess it depends on what language they are coming from if any at all. Mike From o.lenstra at gmail.com Thu Aug 21 21:21:18 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Thu, 21 Aug 2008 21:21:18 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <g8kccl$tsu$1@ger.gmane.org> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> <g8kccl$tsu$1@ger.gmane.org> Message-ID: <3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com> > > > def onScan(self, event): >> self.myfile = open('foo.txt') >> self.count = 0 >> self.setTimer(0.01, self.processLine) >> >> def processLine(self): >> line = self.myfile.readline() >> if line: >> processLine(line) >> > > This function needs to be defined somewhere obviously! > It is a global function not a method of your class. > Ah, I got this mixed up. I thought this was a function built into python. So I would need to define setTimer in the MyClass too. Is there anything that I can read on timers? > > self.count += 1 >> self.myGauge.setValue(count) >> > > And now you access the attribute you created in __init__ above... > Kind of silly to forget not to make a reference to the gauge bar. Got that fixed at least. Thank you so much for replying. Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080821/1c4ae3a0/attachment-0001.htm> From dotancohen at gmail.com Thu Aug 21 21:27:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 22:27:06 +0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <g8kc1h$sia$1@ger.gmane.org> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <g8kc1h$sia$1@ger.gmane.org> Message-ID: <880dece00808211227y2f89b106g16830f5f8db56646@mail.gmail.com> 2008/8/21 Alan Gauld <alan.gauld at btinternet.com>: > "Dotan Cohen" <dotancohen at gmail.com> wrote > >> Let's start from there. I need the startswith() function, but I do not >> know it's name. I search for "strings" and find this: >> 4. String Services >> * 4.1 string -- Common string operations >> o 4.1.3 String functions > > Personally I rarely start with the documentation. > I'd start either with the >>> prompt and the help() > function or I may use dir() as in dir("") to get a list > of all the attributes - including methods - of an object. > If I don't undertand what dir/help tell me, or don't see > anything promising, then I will search the docs. > > So here is my session looking for startwith... > >>>> help("") > >>>> dir("") > > ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', > '__ > ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', > '__g > t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', > '__mul__ > ', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', > '__rmod__', ' > __rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', > 'decode', > 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', > 'isdi > git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', > 'lst > rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', > 'rsplit' > , 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', > 'title', ' > translate', 'upper', 'zfill'] >>>> >>>> help("".startswith) > > Help on built-in function startswith: > > startswith(...) > S.startswith(prefix[, start[, end]]) -> bool > > Return True if S starts with the specified prefix, False otherwise. > With optional start, test S beginning at that position. > With optional end, stop comparing S at that position. > prefix can also be a tuple of strings to try. > > > If I'd done help(str) instead of help("") in the first case > I'd have got the full help screen for string objects including > startswith.. > > Never forget the >>> prompt as a source of research. Oh, I have a lot to learn! Thanks, you have no idea how many different angles have become clear to me because of this post. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From dotancohen at gmail.com Thu Aug 21 21:29:42 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 22:29:42 +0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> Message-ID: <880dece00808211229xf843924k70a71043270a66d8@mail.gmail.com> 2008/8/21 Jerry Hill <malaclypse2 at gmail.com>: > On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen <dotancohen at gmail.com> wrote: >> 2008/8/21 Kent Johnson <kent37 at tds.net>: >>> Chapters 2 and 3 of the library reference are highly recommended. >>> http://docs.python.org/lib/lib.html >> >> Let's start from there. I need the startswith() function, but I do not >> know it's name. I search for "strings" and find this: >> 4. String Services >> * 4.1 string -- Common string operations >> o 4.1.3 String functions > > You went too far. Look at 3.6 (Sequence types) and 3.6.1 (String > Methods). Those document operations that work on all types of > sequences and the methods of the string type. That's 99% of what > you'll need to know about python strings. Kent was pretty specific > about looking at chapter two and three of the library reference. Why > did you start with chapter four instead? That's where my search took me. I use the Vimperator Firefox plugin, and I know that it does not start searching from the start of the page. It seems rather inconsistent, and I think that the developer knows that. > I believe that doc bugs (and suggestions for improvements) are tracked > on the python bug tracker (http://bugs.python.org/). If you're going > to submit doc patches, you may want to take a look at > http://docs.python.org/dev/3.0/ which I believe is the beta of the new > documentation layout for python 3.0. I will definitely look through there, thanks. > I'm not sure how much the actual > contents have changed from the 2.x docs though. I notice that the > section on the string module does now refer you back to the methods of > string and sequences in general, which the current docs do not. Root. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From dotancohen at gmail.com Thu Aug 21 21:31:28 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 21 Aug 2008 22:31:28 +0300 Subject: [Tutor] Tutor Digest, Vol 54, Issue 72 In-Reply-To: <1219340633.6275.35.camel@lieryan-laptop> References: <mailman.20396.1219266360.920.tutor@python.org> <1219340633.6275.35.camel@lieryan-laptop> Message-ID: <880dece00808211231i6c86157ai6df195e2f3e6ebb@mail.gmail.com> 2008/8/21 Lie Ryan <lie.1296 at gmail.com>: > Python is strictly typed (unlike some languages like Javascript), you > cannot compare a string with a number although the string only contains > numbers. sys.argv[...] is a list of strings so preNumber[0] is a string, > while 0 is an integer. Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From jtp at nc.rr.com Thu Aug 21 22:34:12 2008 From: jtp at nc.rr.com (James) Date: Thu, 21 Aug 2008 16:34:12 -0400 Subject: [Tutor] pass argument into running program *outside* of program Message-ID: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> All, I have a program that I am writing that will be shared amongst multiple users. This program sits in the background as a daemon and 'does' things (consider it a black box). I want users to be able to SSH into the Linux box that is running the code and then do something like this: $ program.py addMe <username> <var2> In other words, a user will 'pass' something (an argument, for a lack of better words) into the program that is *already* running, and the program will modify its behavior based on that command. I guess this is equivalent to saying "/etc/init.d/httpd restart", although I imagine the init script is actually telling the program to stop and restart. Thoughts on how to go about doing this, or if it's at all possible? :) Thanks! -j From kent37 at tds.net Thu Aug 21 23:10:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Aug 2008 17:10:03 -0400 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> References: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> Message-ID: <1c2a2c590808211410l4f0dc255k6eec8422c41b19cd@mail.gmail.com> On Thu, Aug 21, 2008 at 4:34 PM, James <jtp at nc.rr.com> wrote: > I have a program that I am writing that will be shared amongst > multiple users. This program sits in the background as a daemon and > 'does' things (consider it a black box). I want users to be able to > SSH into the Linux box that is running the code and then do something > like this: > > $ program.py addMe <username> <var2> > > In other words, a user will 'pass' something (an argument, for a lack > of better words) into the program that is *already* running, and the > program will modify its behavior based on that command. One possibility is for the daemon to be listening on some kind of socket. A web server is one example; in that case the users could load a web page to change the behaviour. Another simple way to do this would be for the daemon to be an xml-rpc server; your addMe program would make an rpc call to the server. This is easy to do with the Python standard library. For example see http://blog.doughellmann.com/2008/06/pymotw-simplexmlrpcserver.html http://blog.doughellmann.com/2008/07/pymotw-xmlrpclib.html Kent From alan.gauld at btinternet.com Fri Aug 22 02:35:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Aug 2008 01:35:45 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <542659.81506.qm@web86704.mail.ukl.yahoo.com><3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com><3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com><g8kccl$tsu$1@ger.gmane.org> <3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com> Message-ID: <g8l1l5$35k$1@ger.gmane.org> "Olrik Lenstra" <o.lenstra at gmail.com> wrote >> def onScan(self, event): >>> self.myfile = open('foo.txt') >>> self.count = 0 >>> self.setTimer(0.01, self.processLine) > > Ah, I got this mixed up. I thought this was a function built into > python. > So I would need to define setTimer in the MyClass too. > Is there anything that I can read on timers? The wx documentation on timers is OK. Here is a very short example program import wx class Counter(wx.Window): def __init__(self, interval=1000): # default of 1 second self.count = 0 self.t = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.onTimer, self.t) self.t.Start(interval, oneShot = True) def onTimer(self, evt): self.upDate() self.t.Start(-1, oneShot=True) def upDate(self): self.count += 1 print "Called by timer event ", self.count class App(wx.Frame): def __init__(self): wx.Frame.__init__(self,None) Counter(self) p = wx.PySimpleApp() f = App() f.Show() p.mainloop() Note this is untested since I don't have wx installed on this PC, but it should be close. You can also use Start(delay, oneShot=False) to create a continuously firing timer. HTH, Alan G From alan.gauld at btinternet.com Fri Aug 22 02:38:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Aug 2008 01:38:53 +0100 Subject: [Tutor] pass argument into running program *outside* of program References: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> Message-ID: <g8l1r2$3ij$1@ger.gmane.org> "James" <jtp at nc.rr.com> wrote > I have a program that I am writing that will be shared amongst > multiple users. This program sits in the background as a daemon and > 'does' things (consider it a black box). I want users to be able to > SSH into the Linux box that is running the code and then do > something > like this: > > $ program.py addMe <username> <var2> create the server with a socket that listens for clients on a port create a client that talks to the socket via that port. See the example in my tutor in the network programming topic. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Aug 22 11:28:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Aug 2008 10:28:44 +0100 Subject: [Tutor] pass argument into running program *outside* of program References: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> <g8l1r2$3ij$1@ger.gmane.org> Message-ID: <g8m0sh$l4b$1@ger.gmane.org> "Alan Gauld" <alan.gauld at btinternet.com> wrote >> $ program.py addMe <username> <var2> > > create the server with a socket that listens for clients on a port > create a client that talks to the socket via that port. > Other options, cruder but arguably simpler, involve sharing a database and using one table for input and another for output. The server polls the input table and writes output to the output table, the clients write requests into the input table and read their results out from the output table. This is surprisingly efficient and scaleable, I've had servers handling several hundred simultaneous clients using this scheme. Its very good where reliability and resiliance are important because even if the machine goes dowen the clients and servers can restart and pick up where they left off. Just a thought... Alan G. From bermanrl at embarqmail.com Fri Aug 22 16:12:47 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Fri, 22 Aug 2008 10:12:47 -0400 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <g8m0sh$l4b$1@ger.gmane.org> References: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> <g8l1r2$3ij$1@ger.gmane.org> <g8m0sh$l4b$1@ger.gmane.org> Message-ID: <48AEC95F.40608@embarqmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080822/e34ad31b/attachment.htm> From jtp at nc.rr.com Fri Aug 22 16:32:35 2008 From: jtp at nc.rr.com (James) Date: Fri, 22 Aug 2008 10:32:35 -0400 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <48AEC95F.40608@embarqmail.com> References: <e107b4ff0808211334m52fb0c11j2b5cd40402dbf8c1@mail.gmail.com> <g8l1r2$3ij$1@ger.gmane.org> <g8m0sh$l4b$1@ger.gmane.org> <48AEC95F.40608@embarqmail.com> Message-ID: <e107b4ff0808220732h38a6f4b1m915d32e628c38b93@mail.gmail.com> Thanks for the responses, folks. I started poking around and another option is Pyro (an alternative to xml-rpc when dealing solely with Python). Thanks again! -j On Fri, Aug 22, 2008 at 10:12 AM, Robert Berman <bermanrl at embarqmail.com> wrote: > > Excellent idea. Its simplicity makes it both doable with ease and very > reliable. Thanks for this suggestion. > > Robert > > Alan Gauld wrote: > > "Alan Gauld" <alan.gauld at btinternet.com> wrote > > $ program.py addMe <username> <var2> > > create the server with a socket that listens for clients on a port > create a client that talks to the socket via that port. > > > Other options, cruder but arguably simpler, involve sharing a database and > using one table for input and another for output. The server polls the input > table and writes output to > the output table, the clients write requests into the input table and read > their results out from the output table. > > This is surprisingly efficient and scaleable, I've had servers handling > several hundred simultaneous clients using this scheme. Its very good where > reliability and resiliance are important because even if the machine goes > dowen the clients and servers can restart and pick up where they left off. > > Just a thought... > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- "Do not meddle in the affairs of wizards, for they are subtle and quick to anger." -Tolkien From lie.1296 at gmail.com Fri Aug 22 18:48:49 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 22 Aug 2008 23:48:49 +0700 Subject: [Tutor] Reformatting phone number In-Reply-To: <mailman.20880.1219335250.920.tutor@python.org> References: <mailman.20880.1219335250.920.tutor@python.org> Message-ID: <1219423729.6882.46.camel@lieryan-laptop> > Message: 4 > Date: Thu, 21 Aug 2008 12:13:58 +0200 > From: "Dotan Cohen" <dotancohen at gmail.com> > Subject: Re: [Tutor] Reformatting phone number > To: OmerT <Jaggojaggo+Py at gmail.com> > Cc: "python-tutor." <tutor at python.org> > Message-ID: > <880dece00808210313w20ef5063ia0ff0cdbd269f286 at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > 2008/8/21 OmerT <Jaggojaggo+Py at gmail.com>: > > mostly, I google "docs.python" and the term or class I'm looking > for. > > Mind, this mainly works for modules or classes which came with the > interpreter. > > > > Exactly- that only works for term, classes, and functions that you > already know the name of. The php docs have a list of all the > functions with a one-line description. It's very easy to find which > funtion performs what one needs. > > I would have never found the startswith() function with the current > document structure. But I suppose that is subject for another thread, > which I am sure would degrade quickly into a flamewar. I don't want to > be the cause of that :) You should also be aware of python's introspection abilities. If you have an object, you could do help(object), dir(object) to get the help file and a dictionary containing the members of the object (if run from a script, you might need to add print statement, e.g. print dir(object) ). In the case of "finding" str.startswith (i.e. a class' members), you could do this from the interactive prompt: >>> help(str) this will print the documentation of str module (and the documentation for all its children too) also, typing: >>> help() will open _interactive_ help with a prompt >>> help('modules') would list all available modules >>> help('keywords') would list all of python's reserved words >>> help('topics') would list some other topics you could pass to help() The "online"[1] help is a very powerful tool, use it often. help() and dir() can also be used from a script, although you might need to add print statement. [1] online refers to the fact that help() is generated from docstrings on-the-fly, it is not related Internet at all. PS: There is also the Internet version of the documentation From lie.1296 at gmail.com Fri Aug 22 19:12:32 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 23 Aug 2008 00:12:32 +0700 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <mailman.21167.1219397347.920.tutor@python.org> References: <mailman.21167.1219397347.920.tutor@python.org> Message-ID: <1219425152.6882.58.camel@lieryan-laptop> > Message: 8 > Date: Fri, 22 Aug 2008 10:28:44 +0100 > From: "Alan Gauld" <alan.gauld at btinternet.com> > Subject: Re: [Tutor] pass argument into running program *outside* of > program > To: tutor at python.org > Message-ID: <g8m0sh$l4b$1 at ger.gmane.org> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > > "Alan Gauld" <alan.gauld at btinternet.com> wrote > > >> $ program.py addMe <username> <var2> > > > > create the server with a socket that listens for clients on a port > > create a client that talks to the socket via that port. > > > > Other options, cruder but arguably simpler, involve > sharing a database and using one table for input and another > for output. The server polls the input table and writes output to > the output table, the clients write requests into the input table > and read their results out from the output table. In a much simpler situation, even a communicating from a plain file could be enough. In the daemon's program folder, there'll be two files: input and output. You write to input to instruct the server and read the response from output. This model is in respect to Unix's philosophy: "make program to handle text streams, because it's the universal interface". > This is surprisingly efficient and scaleable, I've had servers > handling several hundred simultaneous clients using this > scheme. Its very good where reliability and resiliance are > important because even if the machine goes dowen the clients > and servers can restart and pick up where they left off. > > Just a thought... > > Alan G. From emile at fenx.com Fri Aug 22 20:05:12 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 22 Aug 2008 11:05:12 -0700 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <1219425152.6882.58.camel@lieryan-laptop> References: <mailman.21167.1219397347.920.tutor@python.org> <1219425152.6882.58.camel@lieryan-laptop> Message-ID: <g8mv4r$7vl$1@ger.gmane.org> Lie Ryan wrote: > > In a much simpler situation, even a communicating from a plain file > could be enough. In the daemon's program folder, there'll be two files: > input and output. You write to input to instruct the server and read the > response from output. This model is in respect to Unix's philosophy: > "make program to handle text streams, because it's the universal > interface". > I've done this and it works well... one thing to watch out for though is snagging a file before it's completely written. Setting up a semaphore or pausing to allow the file write to complete once seeing the file fixes it adequately. Emile From etrade.griffiths at dsl.pipex.com Fri Aug 22 20:23:18 2008 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Fri, 22 Aug 2008 19:23:18 +0100 Subject: [Tutor] Unicode strings Message-ID: <72lcf4$h2t2o@smtp.pipex.tiscali.co.uk> Hi I am trying to read in non-ASCII data from file using Unicode, with this test app: vocab=[("abends","in the evening"), ("aber","but"), ("die abflughalle","departure lounge"), ("abhauen","to beat it/leave"), ("abholen","to collect/pick up"), ("das Abitur","A-levels"), ("abmachen","to take off"), ("abnehem","to lose weight"), ("die Auff\xFCrung","performance (of a play)"), ("der Au\xDFenhandel","foreign trade") ] print "data from list" for (word1, word2) in vocab: print " ", word1, unicode(word1,"latin1") print "\ndata from file" in_file = open("eng_ger.txt","r") for line in in_file: words = line.split(',') print " ",words[0],unicode(words[0],"latin1") in_file.close() The data in the file"eng_ger.txt" is listed below. When I parse the data from the list, I get the correct text displayed but when reading it from file, the encoding into unicode does not occur. I would be really grateful if someone could explain why the string-> unicode conversion works with lists but not with files! Thanks in advance Alun Griffiths Contents of "eng_ger.txt" abends,in the evening aber,but die abflughalle,departure lounge abhauen,to beat it/leave abholen,to collect/pick up das Abitur,A-levels abmachen,to take off abnehem,to lose weight die Auff\xFCrung,performance (of a play) der Au\xDFenhandel,foreign trade From kent37 at tds.net Fri Aug 22 21:01:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Aug 2008 15:01:27 -0400 Subject: [Tutor] Unicode strings In-Reply-To: <72lcf4$h2t2o@smtp.pipex.tiscali.co.uk> References: <72lcf4$h2t2o@smtp.pipex.tiscali.co.uk> Message-ID: <1c2a2c590808221201w70715a1dx4f61c20522b4f303@mail.gmail.com> On Fri, Aug 22, 2008 at 2:23 PM, eShopping <etrade.griffiths at dsl.pipex.com> wrote: > Hi > > I am trying to read in non-ASCII data from file using Unicode, with this > test app: > > vocab=[("abends","in the evening"), > ("die Auff\xFCrung","performance (of a play)"), > ("der Au\xDFenhandel","foreign trade") The \x escapes are interpreted by the Python parser, they are not part of the string. In other words, the string contains actual latin-1 byte codes. > The data in the file"eng_ger.txt" is listed below. When I parse the data > from the list, I get the correct text displayed but when reading it from > file, the encoding into unicode does not occur. I would be really grateful > if someone could explain why the string-> unicode conversion works with > lists but not with files! > > Thanks in advance > > Alun Griffiths > > Contents of "eng_ger.txt" > > abends,in the evening > die Auff\xFCrung,performance (of a play) > der Au\xDFenhandel,foreign trade Here, the python parser is not interpreting the \x escapes so the file contains actual \x rather than latin-1 characters. Two options: - Create the file with actual latin-1 characters - Use the special 'string-escape' codec to interpret the data from the file, e.g. print " ",words[0],unicode(words[0].decode('string-escape'),"latin1") Kent From o.lenstra at gmail.com Fri Aug 22 21:02:50 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Fri, 22 Aug 2008 21:02:50 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <g8l1l5$35k$1@ger.gmane.org> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> <g8kccl$tsu$1@ger.gmane.org> <3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com> <g8l1l5$35k$1@ger.gmane.org> Message-ID: <3c8f6fd70808221202j395a809ft576010e732b2f6a1@mail.gmail.com> It works! :) My program is now as good as done, only one thing that bothers me a bit. When I click the scan button the GUI Freezes because it is handling the onScan function. Is there any way to prevent this? Regards, Olrik -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080822/509230d4/attachment-0001.htm> From dotancohen at gmail.com Fri Aug 22 22:23:58 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 22 Aug 2008 23:23:58 +0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) Message-ID: <880dece00808221323v12ea4379y59aefa22289411ed@mail.gmail.com> 2008/8/22 Lie Ryan <lie.1296 at gmail.com>: > You should also be aware of python's introspection abilities. If you > have an object, you could do help(object), dir(object) to get the help > file and a dictionary containing the members of the object (if run from > a script, you might need to add print statement, e.g. print > dir(object) ). If I know their names :( > In the case of "finding" str.startswith (i.e. a class' members), you > could do this from the interactive prompt: > >>>> help(str) > this will print the documentation of str module (and the documentation > for all its children too) Good stuff in there, I will spend some time familiarizing myself with those functions. > also, typing: >>>> help() > will open _interactive_ help with a prompt This is great! I had to install some docs as Ubuntu does not install them by default, but that is no problem. >>>> help('modules') > would list all available modules > >>>> help('keywords') > would list all of python's reserved words > >>>> help('topics') > would list some other topics you could pass to help() I will go through them. Thanks. > The "online"[1] help is a very powerful tool, use it often. help() and > dir() can also be used from a script, although you might need to add > print statement. > > [1] online refers to the fact that help() is generated from docstrings > on-the-fly, it is not related Internet at all. PS: There is also the > Internet version of the documentation Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From kent37 at tds.net Fri Aug 22 23:01:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Aug 2008 17:01:29 -0400 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <880dece00808221323v12ea4379y59aefa22289411ed@mail.gmail.com> References: <880dece00808221323v12ea4379y59aefa22289411ed@mail.gmail.com> Message-ID: <1c2a2c590808221401j51983ffdr7ea1027a799f7376@mail.gmail.com> On Fri, Aug 22, 2008 at 4:23 PM, Dotan Cohen <dotancohen at gmail.com> wrote: > 2008/8/22 Lie Ryan <lie.1296 at gmail.com>: >> You should also be aware of python's introspection abilities. If you >> have an object, you could do help(object), dir(object) to get the help >> file and a dictionary containing the members of the object (if run from >> a script, you might need to add print statement, e.g. print >> dir(object) ). > > If I know their names :( Not necessarily. dir(object) will show you the names of the methods of the object, then you can get help on individual methods. For example to explore string methods: dir('') lists all string methods, including e.g. endswith help(''.endswith) gives help for the endswith method Also help(type('')) gives the help for class str without having to know its name. Kent From ricaraoz at gmail.com Fri Aug 22 15:46:47 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 22 Aug 2008 10:46:47 -0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <7941B2693F32294AAF16C26B679A258D035B7056@csomb01.corp.atmel.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D035B7056@csomb01.corp.atmel.com> Message-ID: <48AEC347.4020402@bigfoot.com> Hansen, Mike wrote: >> On Thu, Aug 21, 2008 at 12:01 PM, Dotan Cohen >> <dotancohen at gmail.com> wrote: >>> 2008/8/21 Kent Johnson <kent37 at tds.net>: >>>> Chapters 2 and 3 of the library reference are highly recommended. >>>> http://docs.python.org/lib/lib.html >>> Let's start from there. I need the startswith() function, >> but I do not >>> know it's name. I search for "strings" and find this: >>> 4. String Services >>> * 4.1 string -- Common string operations >>> o 4.1.3 String functions >> You went too far. Look at 3.6 (Sequence types) and 3.6.1 (String >> Methods). Those document operations that work on all types of >> sequences and the methods of the string type. That's 99% of what >> you'll need to know about python strings. Kent was pretty specific >> about looking at chapter two and three of the library reference. Why >> did you start with chapter four instead? >> >>> But on that page, this is all there is: >>> """ >>> The following functions are available to operate on string >> and Unicode >>> objects. They are not available as string methods. >> ... >>> So Python has only two string functions? That's what it looks like. >> There are only two (non-deprecated) functions in the string module. >> >>> Thanks, Kent. I will be a nuisance! Is there any place to suggest >>> improvements to the docs? I see on the python.org site it >> is suggested >>> to email website bugs to the site admin. Does that go for >> the docs? I >>> am not the one to improve them at this time, as I am unfamiliar with >>> the language, but I could report usability issues such as that >>> mentioned here. >> I believe that doc bugs (and suggestions for improvements) are tracked >> on the python bug tracker (http://bugs.python.org/). If you're going >> to submit doc patches, you may want to take a look at >> http://docs.python.org/dev/3.0/ which I believe is the beta of the new >> documentation layout for python 3.0. I'm not sure how much the actual >> contents have changed from the 2.x docs though. I notice that the >> section on the string module does now refer you back to the methods of >> string and sequences in general, which the current docs do not. >> >> -- >> Jerry >> _______________________________________________ > > I can't put my finger on it, but there's something lacking in the > docs. They are not terrible, but they aren't fantastic either. I'm not > entirely sure what I'd do to fix them. I usually rely on Learning > Python, The Python Standard Library, the Global Module Index section > of the docs, and sometimes Python in a Nutshell. I need to get in the > habit of using help in the shell. Sometimes the docs for a particular > module might be a little obtuse for me especially if it doesn't have > example code. That's where The Python Standard Library book comes in > handy since it has example code. After experimenting in the shell, if > I really get stuck, I'll ask on this list. Maybe having tags or > something to help with searches. On the string methods page, have a > tag called "string functions". I don't think many new to the language > are going to know that they are called "string methods" and not "string > functions". I guess it depends on what language they are coming from > if any at all. Python Manuals are pretty good from my POV. You go to "Index" tab and type "string", the first entry will get you to the "String Methods" page. Just a matter of seconds. What I find lacking in the docs are a link to a code example for every item and a "See Also" link to other related items. With some modules I can't make sense of the different bits and pieces till I see a code example, and I think this would be the greatest improvement to the actually very good docs. From alan.gauld at btinternet.com Sat Aug 23 01:41:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Aug 2008 00:41:19 +0100 Subject: [Tutor] Problems with Gauge Bar. References: <542659.81506.qm@web86704.mail.ukl.yahoo.com><3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com><3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com><g8kccl$tsu$1@ger.gmane.org><3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com><g8l1l5$35k$1@ger.gmane.org> <3c8f6fd70808221202j395a809ft576010e732b2f6a1@mail.gmail.com> Message-ID: <g8niqv$8m4$1@ger.gmane.org> "Olrik Lenstra" <o.lenstra at gmail.com> wrote > When I click the scan button the GUI Freezes because it is handling > the > onScan function. > Is there any way to prevent this? This is back to where we started in that you need to break the onScan function down such that you only process a portion of the data before resetting the timer. Everytime you restart the timer control will revert to the GUI untill the timer next fires. If you are unsure how to do that you will need to show us some code. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Aug 23 01:47:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Aug 2008 00:47:44 +0100 Subject: [Tutor] pass argument into running program *outside* of program References: <mailman.21167.1219397347.920.tutor@python.org> <1219425152.6882.58.camel@lieryan-laptop> Message-ID: <g8nj71$9gc$1@ger.gmane.org> "Lie Ryan" <lie.1296 at gmail.com> wrote >> sharing a database and using one table for input and another >> for output. The server polls the input table and writes output to > > In a much simpler situation, even a communicating from a plain file > could be enough. In the daemon's program folder, there'll be two > files: The problem with text files for this is that it seriously limits the number of clients because locking is applied at the file level, whereas with a database locking is generally applied at the row level. Also databases tend to support triggers that only fire the server process when something actually gets written. For files you really need to poll the file (although some OS might support select() monitoring of a file - but by then sockets are easier! :-) But if you only have one client then a file will certainly work just as well. Alan G From o.lenstra at gmail.com Sat Aug 23 02:05:43 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sat, 23 Aug 2008 02:05:43 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <g8niqv$8m4$1@ger.gmane.org> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> <g8kccl$tsu$1@ger.gmane.org> <3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com> <g8l1l5$35k$1@ger.gmane.org> <3c8f6fd70808221202j395a809ft576010e732b2f6a1@mail.gmail.com> <g8niqv$8m4$1@ger.gmane.org> Message-ID: <3c8f6fd70808221705y79dbe609t3e77cfc7eea45704@mail.gmail.com> I attached the whole program. I'm pretty sure I made a lot of beginners mistakes, if you see something drastically wrong feel free to point it out ;-) Regards, Olrik 2008/8/23 Alan Gauld <alan.gauld at btinternet.com> > > "Olrik Lenstra" <o.lenstra at gmail.com> wrote > > When I click the scan button the GUI Freezes because it is handling the >> onScan function. >> Is there any way to prevent this? >> > > This is back to where we started in that you need to break > the onScan function down such that you only process a portion > of the data before resetting the timer. Everytime you restart the > timer control will revert to the GUI untill the timer next fires. > > If you are unsure how to do that you will need to show us some > code. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080823/5a4e1ea0/attachment-0001.htm> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: TSO.pyw URL: <http://mail.python.org/pipermail/tutor/attachments/20080823/5a4e1ea0/attachment-0001.txt> From lawfulfalafel at gmail.com Sat Aug 23 02:46:25 2008 From: lawfulfalafel at gmail.com (lawful falafel) Date: Fri, 22 Aug 2008 20:46:25 -0400 Subject: [Tutor] Problem with creating a class to access a 2d array Message-ID: <c22a4930808221746w65f2a576v2c44185ea94c860c@mail.gmail.com> Hello, I am currently trying to teach myself python. This isnt my first language, as I used to be quite good at using java. But it seems to be a bit harder for me to understand some stuff. Right now, in trying to teach myself the language, I thought I would make a simple text based game, like Zork or Adventure or whatever. Anyway, right now I am trying to create the map generating function, and I am not exactly sure what to do. Here is all of the code I have so far: ------------ class Map(): def __init__(self): self.make_map() def make_map(): #first create array to store data map = [][] for x in range(10): for y in range(10): map[x][y] = map_random() def map_random(): #This would do something simple, such as deciding whether #this is grass or gravel terrain and if there is an object #nearby ------------- I really like python, but the one thing I really hate is that most of the tutorials treat it like interactive scripting instead of object oriented development, which really confuses me. So basically right now I dont even know what equivelent version of main() I would write. I also dont understand how I could write an accessing method so that I could write Map(1,2), since the only place that deals with arguments is the __init__ function I think, and that doesnt seem to deal with arguments. Any help or links to sites about python and OO stuff would really be appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080822/7138cfbe/attachment.htm> From srilyk at gmail.com Sat Aug 23 03:09:16 2008 From: srilyk at gmail.com (W W) Date: Fri, 22 Aug 2008 20:09:16 -0500 Subject: [Tutor] Problem with creating a class to access a 2d array In-Reply-To: <c22a4930808221746w65f2a576v2c44185ea94c860c@mail.gmail.com> References: <c22a4930808221746w65f2a576v2c44185ea94c860c@mail.gmail.com> Message-ID: <333efb450808221809s4b9f1928x72c78934819f9052@mail.gmail.com> On Fri, Aug 22, 2008 at 7:46 PM, lawful falafel <lawfulfalafel at gmail.com>wrote: > I really like python, but the one thing I really hate is that most of the > tutorials treat it like interactive scripting instead of object oriented > development, which really confuses me. So basically right now I dont even > know what equivelent version of main() I would write. I also dont understand > how I could write an accessing method so that I could write Map(1,2), since > the only place that deals with arguments is the __init__ function I think, > and that doesnt seem to deal with arguments. Any help or links to sites > about python and OO stuff would really be appreciated. > well, if it helps you feel familiar, you could write: def main(): # call some functions here But in reality, anything that's not defined in a function will be executed at runtime. I don't have much experience with classes, so I'm sure someone else would be of more help there. but I hope I've helped a bit. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080822/f733fe42/attachment.htm> From billburns at pennswoods.net Sat Aug 23 04:39:28 2008 From: billburns at pennswoods.net (Bill Burns) Date: Fri, 22 Aug 2008 22:39:28 -0400 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <3c8f6fd70808221202j395a809ft576010e732b2f6a1@mail.gmail.com> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> <g8kccl$tsu$1@ger.gmane.org> <3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com> <g8l1l5$35k$1@ger.gmane.org> <3c8f6fd70808221202j395a809ft576010e732b2f6a1@mail.gmail.com> Message-ID: <48AF7860.2060209@pennswoods.net> Olrik Lenstra wrote: > It works! :) > My program is now as good as done, only one thing that bothers me a bit. > When I click the scan button the GUI Freezes because it is handling the > onScan function. > Is there any way to prevent this? > > Regards, > Olrik You might try adding wx.SafeYield(self, True) inside of the onScan method. HTH, Bill From wescpy at gmail.com Sat Aug 23 09:00:40 2008 From: wescpy at gmail.com (wesley chun) Date: Sat, 23 Aug 2008 00:00:40 -0700 Subject: [Tutor] Problem with creating a class to access a 2d array In-Reply-To: <c22a4930808221746w65f2a576v2c44185ea94c860c@mail.gmail.com> References: <c22a4930808221746w65f2a576v2c44185ea94c860c@mail.gmail.com> Message-ID: <78b3a9580808230000s6f3a7feqbf55120df17d7251@mail.gmail.com> > I am currently trying to teach myself python. This isnt my first language, > as I used to be quite good at using java. you are in good shape... you will only need to "tweak" some of your notions with regards to Java for Python, and you will be in good shape. > I really like python, but the one thing I really hate is that most of the > tutorials treat it like interactive scripting instead of object oriented > development, which really confuses me. one of Python's strengths is that it can be used for both interactive scripting as well as to develop fully object-oriented software applications. tutorials tend towards the former only because Python is also very popular as a first language for those completely new to programming. i'm sure someone on this list can point you to a more object-focused intro to Python. > So basically right now I dont even > know what equivelent version of main() I would write. I also dont understand > how I could write an accessing method so that I could write Map(1,2), since > the only place that deals with arguments is the __init__ function I think, > and that doesnt seem to deal with arguments. > class Map(): > def __init__(self): > self.make_map() minor syntax fix: change your class declaration to either "class Map:" or "class Map(object):". then to instantiate, instead of using "Map map = new Map();", you would do "map = Map()". to tweak your initializer -- Python's aren't really "constructors" -- you can do this: def __init__(self, x, y): self.make_map(x, y) # or whatever method you have that takes input if you want x and y to be optional, you can set default values for x, y: def __init__(self, x=0, y=0): # same as whatever you had > def make_map(): > #first create array to store data > map = [][] > for x in range(10): > for y in range(10): > map[x][y] = map_random() in Python, you don't have to predeclare arrays. you could if you wanted, by using a list comprehension for small 2-dim arrays (or generator expressions if much larger)... here's an example to put in a placeholder of None (which is like Java's null): >>> [[None for y in range(10)] for x in range(10)] [[None, None, None, None, None, None, None, None, None, None], [None, None, ...<snip>... None, None, None]] better yet, you can fill in whatever random value you wanted: [[map_random() for y in range(10)] for x in range(10)] here is another construct where you create pairs of 2-tuples, making up a 1-dimension array rather than multidim: >>> [(x,y) for x in range(10) for y in range(10)] [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1), ...<snip>... (9, 8), (9, 9)] in Core Python, i do give a pretty lengthy write up on doing OOP with Python, so i'd invite you to take a look if you get a chance. hope this helps, and welcome to Python! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Sat Aug 23 10:52:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Aug 2008 09:52:22 +0100 Subject: [Tutor] Problem with creating a class to access a 2d array References: <c22a4930808221746w65f2a576v2c44185ea94c860c@mail.gmail.com> Message-ID: <g8oj47$e38$1@ger.gmane.org> "lawful falafel" <lawfulfalafel at gmail.com> wrote > I really like python, but the one thing I really hate is that most > of the > tutorials treat it like interactive scripting instead of object > oriented > development, which really confuses me. Can you explain what confuses you about that? The original Object Oriented languages (aside from Simula) were nearly all interactive, interpreted languages with promt driven development similar to Python - look at Lisp, SmallTalk etc. So Object Oriented Development is very amenable to using an interactive prompt (or workspace in Smalltalk terms). OO development is all about building objects (via classes) and testing them. When you have enough objects you glue them together into a bigger object and so on. Evolving objects using a prompt is one of the fastest and most effective ways of building objects that I know. > know what equivelent version of main() I would write. You donl;t need a main. In fact main is an artifact of C that got carried into C++ and Java but is not at all related to OOP. Many OOP purists would maintain that a main() method/function is non OOP. You should just need to instantiate the application and it will start running itself. You can do that in Python if you want, or you can write a main() function if you prefer that. > how I could write an accessing method so that I could write > Map(1,2), since > the only place that deals with arguments is the __init__ function I > think, No, any method can take arguments. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eric at ericabrahamsen.net Sat Aug 23 12:47:15 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Sat, 23 Aug 2008 18:47:15 +0800 Subject: [Tutor] __iter__ loops, partitioning list among children Message-ID: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> Hi, I've got a problem that takes a bit of explaining, but it's relatively simple when you get down to it. This is another django-related thing, but the issue itself is pure python. I made a custom class, called an EventEngine, which represents a span of time. You initialize it with a queryset/list of django model instances, and the resulting EventEngine object has an 'events' attribute, which is a queryset/list of model instances that fall within that span of time, according to a datetime attribute on the django model. Next come EventEngine subclasses, representing commonly used spans of time ? Month, Week, Day, etc. The EventEngine __iter__ method is overridden so that each of these subclasses, when iterated over, produces child instances of the next smallest EventEngine subclass. Iterating on a Month produces Weeks, iterating on a Week produces Days and so on. As each parent produces its children, the events in the 'events' attribute get partitioned out to the children as appropriate to their date ranges. Right now I'm doing this as stupidly as possible: for each child 'c' in the parent, I loop over all the parent events, and append them to c.events if their date attribute falls within the child's date range: for e in self.events: if c.start <= getattr(e,self.start_attr) < c.stop: c.events.append(e) This is stupid for (at least) two reasons: 1) it evaluates the entire queryset and sticks it in memory with the first child instance, obviating the whole point of an iterable, and 2) it loops over the entire event list for every child, even though the list is already properly sorted by date, and we could break from the loop with the first event that falls outside the child's date range. Performance is important, as some madman could initialize a Year with a huge queryset, and do nested iterations all the way down to Minute. So I've got a few considerations: 1. The parent's events queryset should only be evaluated as much as is needed to yield one child at a time. 2. The parent's events queryset should not be duplicated as it is distributed among the children, ie it should make references and not copies (I don't know how to make sure this happens). 3. I don't want to empty the parent's 'events' list as it is distributed among the children, as other methods depend on the list being there. 4. The events attribute of the 'top level' instance is a django queryset, but it will be a list for all descendent instances (they can be nested arbitrarily deeply). This limits the number of functions available ? ie you can't pop() a django queryset. At first I thought the bisect module was the way to go, but it is too tightly tied to integer list indices, and works very awkwardly when bisecting on datetime attributes. List slices produce copies, unless I'm mistaken. Something tells me that a plain old while loop with a break might do the trick, but I can't quite see it clear. Ideally this would be something that starts iterating where the date attribute falls into the right range, and then stops iterating as soon as it passes out of that range. Probably I'll have to settle for just one or the other, but one can dream. Thanks for reading all this. I'm hoping that all the restrictions and conditions will make the solution more obvious, rather than less obvious, to those who know more than I... --Eric From o.lenstra at gmail.com Sat Aug 23 13:23:59 2008 From: o.lenstra at gmail.com (Olrik Lenstra) Date: Sat, 23 Aug 2008 13:23:59 +0200 Subject: [Tutor] Problems with Gauge Bar. In-Reply-To: <48AF7860.2060209@pennswoods.net> References: <542659.81506.qm@web86704.mail.ukl.yahoo.com> <3c8f6fd70808111520r1c048e22r51d43fa8c0219dd5@mail.gmail.com> <3c8f6fd70808210927o58a94c78q87cfe58aa4bd87b1@mail.gmail.com> <g8kccl$tsu$1@ger.gmane.org> <3c8f6fd70808211221l8c1c95auf61bf27f9335be0c@mail.gmail.com> <g8l1l5$35k$1@ger.gmane.org> <3c8f6fd70808221202j395a809ft576010e732b2f6a1@mail.gmail.com> <48AF7860.2060209@pennswoods.net> Message-ID: <3c8f6fd70808230423v3949e8bbg9317e9dbd695cd81@mail.gmail.com> Thanks Bill. That does work! Thanks a lot! :) Regards, Olrik 2008/8/23 Bill Burns <billburns at pennswoods.net> > Olrik Lenstra wrote: > >> It works! :) >> My program is now as good as done, only one thing that bothers me a bit. >> When I click the scan button the GUI Freezes because it is handling the >> onScan function. >> Is there any way to prevent this? >> >> Regards, >> Olrik >> > > You might try adding wx.SafeYield(self, True) inside of the onScan method. > > HTH, > > Bill > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080823/b6624d25/attachment.htm> From lie.1296 at gmail.com Sat Aug 23 15:50:53 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 23 Aug 2008 20:50:53 +0700 Subject: [Tutor] Problem with creating a class to access a 2d array In-Reply-To: <mailman.53.1219485620.11633.tutor@python.org> References: <mailman.53.1219485620.11633.tutor@python.org> Message-ID: <1219499453.6290.60.camel@lieryan-laptop> On Sat, 2008-08-23 at 12:00 +0200, tutor-request at python.org wrote: > > Message: 1 > Date: Fri, 22 Aug 2008 20:46:25 -0400 > From: "lawful falafel" <lawfulfalafel at gmail.com> > Subject: [Tutor] Problem with creating a class to access a 2d array > To: tutor at python.org > Message-ID: > <c22a4930808221746w65f2a576v2c44185ea94c860c at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hello, > > I am currently trying to teach myself python. This isnt my first > language, > as I used to be quite good at using java. But it seems to be a bit > harder > for me to understand some stuff. Right now, in trying to teach myself > the > language, I thought I would make a simple text based game, like Zork > or > Adventure or whatever. Anyway, right now I am trying to create the map > generating function, and I am not exactly sure what to do. > > Here is all of the code I have so far: > > ------------ > > class Map(): > def __init__(self): > self.make_map() __init__ can take arguments, like this: def __init__(self, x, y): self.make_map(x, y) > def make_map(): You've got to receive self[1] on EVERY instance method. This is because python's instance method access is actually like this: class A(object): def instance_method(self, args): print args a = A() # this a.instance_method(args) # is translated into this A.instance_method(a, args) [1] Actually you can use any valid python name in place of self, but the use of the name self is an extremely strong convention > #first create array to store data > map = [][] that is a syntax Error. > for x in range(10): > for y in range(10): > map[x][y] = map_random() In python, your variable 'map' and 'map_random' are local names that are accessible only within the function and destroyed when the function exits. To access and manipulate an instance variable, which is accessible within the instance, use self.map and self.map_random, this is similar to C's (and I think Java's) "this". > def map_random(): > #This would do something simple, such as deciding whether > #this is grass or gravel terrain and if there is an object > #nearby In python, the module to use is random import random print random.randrange(0, 100) # 0-99, just like range() print random.randint(0, 100) # 0-100 print random.choice(['grass', 'gravel', 'mud']) > ------------- > > I really like python, but the one thing I really hate is that most of > the > tutorials treat it like interactive scripting instead of object > oriented > development, which really confuses me. Simply because it is usually easier to explain things in interactive mode. I found that most tutorials that explain things in source code file is usually unable to explain things in an easy to understand manner (e.g. Microsoft's MSDN). Sure there are a few good ones, most not. > So basically right now I dont even > know what equivelent version of main() I would write. You don't write main() function in python (although you can if you insist). A simple python program would usually just start with codes on the root level: print 'Hello, this is a simple program' print 'Enter A or B' answer = raw_input() if answer == 'A': print 'you answered A' elif answer == 'B": print 'you answered B' else: print 'I don't understand' print 'Bye' In a more complex program, you usually have an initial function to be run (i.e. main-like function) # define a function def main(): print 'Hello, this is a simple program' print 'Enter A or B' answer = raw_input() if answer == 'A': print 'you answered A' elif answer == 'B": print 'you answered B' else: print 'I don't understand' print 'Bye' # run the function main() print 'Exiting' but this could be problematic if your program is intended to be imported, so this boilerplate of __name__ == '__init__' has appeared: # define a function def main(): print 'Hello, this is a simple program' print 'Enter A or B' answer = raw_input() if answer == 'A': print 'you answered A' elif answer == 'B": print 'you answered B' else: print 'I don't understand' print 'Bye' # run the function if __name__ == '__main__': main() print 'Exiting' An even more complex program wouldn't just have a main() function, but a "main" object > I also dont understand > how I could write an accessing method so that I could write Map(1,2), > since > the only place that deals with arguments is the __init__ function I > think, > and that doesnt seem to deal with arguments. Why do you think so? There is a reason it's called __init__ not __new__, it's because, unlike a constructor[2], __init__'s job is not to return a new object of that class, but to initialize the instance to a usable state [2] In python, there is a constructor: __new__, but because of the design of python most programs wouldn't need to touch it. > Any help or links to sites > about python and OO stuff would really be appreciated. From sierra_mtnview at sbcglobal.net Sat Aug 23 15:56:19 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 23 Aug 2008 06:56:19 -0700 Subject: [Tutor] Python open of c:\ path Problem Message-ID: <48B01703.2010900@sbcglobal.net> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080823/fa3181cc/attachment.htm> From kent37 at tds.net Sat Aug 23 17:05:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Aug 2008 11:05:19 -0400 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <48AEC347.4020402@bigfoot.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D035B7056@csomb01.corp.atmel.com> <48AEC347.4020402@bigfoot.com> Message-ID: <1c2a2c590808230805j35f220ekd03738148922ccef@mail.gmail.com> On Fri, Aug 22, 2008 at 9:46 AM, Ricardo Ar?oz <ricaraoz at gmail.com> wrote: > What I find lacking in the docs are a link to a code example for every item > and a "See Also" link to other related items. With some modules I can't make > sense of the different bits and pieces till I see a code example, and I > think this would be the greatest improvement to the actually very good docs. You might like Doug Hellman's Python Module of the Week pages. He gives exhaustive examples of each module. http://www.doughellmann.com/projects/PyMOTW/ Kent From kent37 at tds.net Sat Aug 23 17:22:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Aug 2008 11:22:37 -0400 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> Message-ID: <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> On Sat, Aug 23, 2008 at 6:47 AM, Eric Abrahamsen <eric at ericabrahamsen.net> wrote: > At first I thought the bisect module was the way to go, but it is too > tightly tied to integer list indices, and works very awkwardly when > bisecting on datetime attributes. I'm not sure what the problem is with bisect (to find the starting point). Your list of model elements has integer indices. I think you have to write a __cmp__ method for your model class that compares on the datetime attribute, then it should work. You can also create a list of (key, model) and sort/search that. http://www.mail-archive.com/python-list at python.org/msg189443.html > List slices produce copies, unless I'm > mistaken. List slices copy the references in the list, not the values. I.e. it is not a deep copy. So you will have only one copy of each model instance even if you slice up the list. So, unless your lists are very large or you have many levels in your hierarchy, this might work. Kent From kent37 at tds.net Sat Aug 23 17:29:35 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Aug 2008 11:29:35 -0400 Subject: [Tutor] Python open of c:\ path Problem In-Reply-To: <48B01703.2010900@sbcglobal.net> References: <48B01703.2010900@sbcglobal.net> Message-ID: <1c2a2c590808230829k38c1db25h219c7e84a09ed4b6@mail.gmail.com> On Sat, Aug 23, 2008 at 9:56 AM, Wayne Watson <sierra_mtnview at sbcglobal.net> wrote: > Python doesn't like this: > > junkfile = open('c:\tmp\junkpythonfile','w') > > I get > junkfile = open('c:\tmp\junkpythonfile','w') > IOError: [Errno 2] No such file or directory: 'c:\tmp\\junkpythonfile' The \ character is a special 'escape' character that is used to insert non-printing characters into a string. \t represents a single tab character, not the two characters \ and t. To put an actual backslash into a string, you can either double it: 'c:\\tmp\\junkpythonfile' or prefix the string with r to make a 'raw' string, which doesn't have any special meaning for \: r'c:\tmp\junkpythonfile' Kent From tomonzob_1 at hotmail.co.uk Sat Aug 23 19:27:21 2008 From: tomonzob_1 at hotmail.co.uk (Tom Wakelam) Date: Sat, 23 Aug 2008 17:27:21 +0000 Subject: [Tutor] Adding Lists? Message-ID: <BAY126-W363B36EF66F58D324E1858FC650@phx.gbl> Hi, hope i've got the email right, and you can help If i have a list of integers, could i then total up the list? e.g. range (1, 5) gives [1, 2, 3, 4] which is easily totalled at 10, yet if i wrote range (1, 500, 2) [1, 3, 5, 7....... ..499] is there a command where i could total that list quickly? Many thanks, Tom _________________________________________________________________ Make a mini you on Windows Live Messenger! http://clk.atdmt.com/UKM/go/107571437/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080823/e641f92c/attachment.htm> From tmz at pobox.com Sat Aug 23 19:47:05 2008 From: tmz at pobox.com (Todd Zullinger) Date: Sat, 23 Aug 2008 13:47:05 -0400 Subject: [Tutor] Python open of c:\ path Problem In-Reply-To: <1c2a2c590808230829k38c1db25h219c7e84a09ed4b6@mail.gmail.com> References: <48B01703.2010900@sbcglobal.net> <1c2a2c590808230829k38c1db25h219c7e84a09ed4b6@mail.gmail.com> Message-ID: <20080823174705.GP21166@inocybe.teonanacatl.org> Kent Johnson wrote: > The \ character is a special 'escape' character that is used to insert > non-printing characters into a string. \t represents a single tab > character, not the two characters \ and t. > > To put an actual backslash into a string, you can either double it: > 'c:\\tmp\\junkpythonfile' > or prefix the string with r to make a 'raw' string, which doesn't have > any special meaning for \: > r'c:\tmp\junkpythonfile' While I don't use Windows myself, I'm believe that you can also use forward-slashes as the path separator, e.g.: junkfile = open('c:/tmp/junkpythonfile','w') (Pardon me if I'm completely wrong.) -- Todd OpenPGP -> KeyID: 0xBEAF0CE3 | URL: www.pobox.com/~tmz/pgp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To grasp the true meaning of socialism, imagine a world where everything is designed by the post office, even the sleaze. -- P.J. O'Rourke -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 542 bytes Desc: not available URL: <http://mail.python.org/pipermail/tutor/attachments/20080823/696fb1b0/attachment.pgp> From emile at fenx.com Sat Aug 23 20:02:26 2008 From: emile at fenx.com (Emile van Sebille) Date: Sat, 23 Aug 2008 11:02:26 -0700 Subject: [Tutor] Adding Lists? In-Reply-To: <BAY126-W363B36EF66F58D324E1858FC650@phx.gbl> References: <BAY126-W363B36EF66F58D324E1858FC650@phx.gbl> Message-ID: <g8pjbl$4id$1@ger.gmane.org> Tom Wakelam wrote: > yet if i wrote range (1, 500, 2) [1, 3, 5, 7....... ..499] is there a > command where i could total that list quickly? > You're looking for sum -- sum(range (1, 500, 2) ) From dsarmientos at gmail.com Sat Aug 23 22:34:47 2008 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Sat, 23 Aug 2008 15:34:47 -0500 Subject: [Tutor] Graphically Display Binary Trees Message-ID: <d356a5240808231334o2f2a4428we4da48eb59cad585@mail.gmail.com> Hi I am working on a red-black binary tree class. I would like to print it in a nice, graphical way. I have never done any GUI programming, or generated any graphics in python, before. What libraries would you use, what's the most straight forward way to achieve what I want? Thank you. From cfuller084 at thinkingplanet.net Sat Aug 23 23:22:41 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 23 Aug 2008 16:22:41 -0500 Subject: [Tutor] Graphically Display Binary Trees In-Reply-To: <d356a5240808231334o2f2a4428we4da48eb59cad585@mail.gmail.com> References: <d356a5240808231334o2f2a4428we4da48eb59cad585@mail.gmail.com> Message-ID: <200808231622.41951.cfuller084@thinkingplanet.net> Graphviz (http://www.graphviz.org/) is great for this sort of thing, but it's an external program. There is a Python interface, pydot (http://dkbza.org/pydot.html) Cheers On Saturday 23 August 2008 15:34, Daniel Sarmiento wrote: > Hi > > I am working on a red-black binary tree class. I would like to print > it in a nice, graphical way. I have never done any GUI programming, or > generated any graphics in python, before. > > What libraries would you use, what's the most straight forward way to > achieve what I want? > > Thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Aug 24 01:25:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Aug 2008 00:25:18 +0100 Subject: [Tutor] Adding Lists? References: <BAY126-W363B36EF66F58D324E1858FC650@phx.gbl> <g8pjbl$4id$1@ger.gmane.org> Message-ID: <g8q690$nd0$1@ger.gmane.org> "Emile van Sebille" <emile at fenx.com> wrote >> yet if i wrote range (1, 500, 2) [1, 3, 5, 7....... ..499] is there >> a command where i could total that list quickly? >> > > You're looking for sum -- > sum(range (1, 500, 2) ) Or on older Python versions reduce: import operator s = reduce(operator.add, range(1,500,2)) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Aug 24 01:21:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Aug 2008 00:21:45 +0100 Subject: [Tutor] Python open of c:\ path Problem References: <48B01703.2010900@sbcglobal.net> Message-ID: <g8q62a$msi$1@ger.gmane.org> "Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote > junkfile = open('c:\tmp\junkpythonfile','w') > IOError: [Errno 2] No such file or directory: > 'c:\tmp\\junkpythonfile' > > I suspect the problem is with the back slash. Comments? Correct. There are several ways round this, the simplest being to use forward slashes which are effectively portable across most OSs. junkfile = open('c:/tmp/junkpythonfile','w') You could use a raw string by prefixing the string with r junkfile = open(r'c:\tmp\junkpythonfile','w') Or you could escape the backslash junkfile = open('c:\\tmp\\junkpythonfile','w') > BTW, how does one continue a long statement > that has, say, a long path to a file? You can create a long string by adding the shorter string elements : f = open( "a:/very/long/path/name/that/needs/a/whole/line/to./itself.py", "w") becomes f = open("a:/very/long/path/name/" + "that/needs/a/whole/" + "line/to./itself.py","w") or by using a line continuation character. f = open("a:/very/long/path/name/" \ "that/needs/a/whole/" \ "line/to./itself.py", "w") HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at gmail.com Sun Aug 24 03:03:37 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 23 Aug 2008 21:03:37 -0400 Subject: [Tutor] Adding Lists? In-Reply-To: <g8q690$nd0$1@ger.gmane.org> References: <BAY126-W363B36EF66F58D324E1858FC650@phx.gbl> <g8pjbl$4id$1@ger.gmane.org> <g8q690$nd0$1@ger.gmane.org> Message-ID: <48B0B369.4070500@gmail.com> Alan Gauld wrote: > > "Emile van Sebille" <emile at fenx.com> wrote > >>> yet if i wrote range (1, 500, 2) [1, 3, 5, 7....... ..499] is there >>> a command where i could total that list quickly? >>> >> >> You're looking for sum -- >> sum(range (1, 500, 2) ) > > Or on older Python versions reduce: > > import operator > s = reduce(operator.add, range(1,500,2)) This is good to know about, as: (1) the operator module has methods for all native operators e.g., s = reduce(operator.mul, range(1,500,2)) to get the product. (2) one may use any function as the first argument to reduce e.g., reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5) (the sum) -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From mwalsh at mwalsh.org Sun Aug 24 04:26:22 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sat, 23 Aug 2008 21:26:22 -0500 Subject: [Tutor] Python open of c:\ path Problem In-Reply-To: <g8q62a$msi$1@ger.gmane.org> References: <48B01703.2010900@sbcglobal.net> <g8q62a$msi$1@ger.gmane.org> Message-ID: <48B0C6CE.1090700@mwalsh.org> Alan Gauld wrote: > "Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote > >> BTW, how does one continue a long statement >> that has, say, a long path to a file? > > You can create a long string by adding the shorter string > elements : > > f = open( > "a:/very/long/path/name/that/needs/a/whole/line/to./itself.py", > "w") > > becomes > > f = open("a:/very/long/path/name/" + > "that/needs/a/whole/" + > "line/to./itself.py","w") > > > or by using a line continuation character. > > f = open("a:/very/long/path/name/" \ > "that/needs/a/whole/" \ > "line/to./itself.py", "w") > or just f = open("a:/very/long/path/name/" "that/needs/a/whole/" "line/to./itself.py", "w") because of the enclosing parentheses. This works for expressions in brackets or braces as well -- any enclosing form. PEP8[1] suggests this as the preferred style (adding that "sometimes using a backslash looks better"), which is a little surprising to me, but not in a bad way. Then again, perhaps I've misunderstood -- which would *not* be surprising. # for those who aren't familiar [1] http://www.python.org/dev/peps/pep-0008/ HTH, Marty From betopm at live.com.mx Sun Aug 24 08:31:28 2008 From: betopm at live.com.mx (Alberto Perez) Date: Sun, 24 Aug 2008 01:31:28 -0500 Subject: [Tutor] hi... Message-ID: <BLU139-W4598415CA35B55905B631899640@phx.gbl> I have a problem with python, I'm begginner in python. How clear the screen of GUI python interactive???? and which is the difference between interactive mode and not interactive mode???? because when I run a program in interactive mode, the program run very good, but if run in not interactive mode not show me error, but the return of function returns no value, this is the source code: def suma(no1,no2): total=no1+no2 return total print 'hola'opcion=input()if opcion==1: print 'suma' a=input() b=input() suma(a,b) the result of this code is: hola1suma57>>> totalTraceback (most recent call last): File "<pyshell#0>", line 1, in <module> totalNameError: name 'total' is not defined>>> why this happens??? what I did wrong??? and why run very good in interactive mode??? thanks for help me and sorry for my bad english, I from Mexico and I english student. Thank you. _________________________________________________________________ Juega y gana, tenemos 3 Xbox a la semana. http://club.prodigymsn.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080824/5a36675b/attachment.htm> From srilyk at gmail.com Sun Aug 24 14:18:02 2008 From: srilyk at gmail.com (W W) Date: Sun, 24 Aug 2008 07:18:02 -0500 Subject: [Tutor] Fwd: hi... In-Reply-To: <333efb450808240517r77f178d8k4cbd85fc9c3fa57c@mail.gmail.com> References: <BLU139-W4598415CA35B55905B631899640@phx.gbl> <333efb450808240517r77f178d8k4cbd85fc9c3fa57c@mail.gmail.com> Message-ID: <333efb450808240518p2b8a745ex7e9905e6c929148c@mail.gmail.com> ---------- Forwarded message ---------- From: W W <srilyk at gmail.com> Date: Sun, Aug 24, 2008 at 7:17 AM Subject: Re: [Tutor] hi... To: Alberto Perez <betopm at live.com.mx> On Sun, Aug 24, 2008 at 1:31 AM, Alberto Perez <betopm at live.com.mx> wrote: > I have a problem with python, I'm begginner in python. How clear the > screen of GUI python interactive???? > I'm not really aware of a way, other than to exit and restart. Is there any particular reason you need/want to? > and which is the difference between interactive mode and not interactive > mode???? > interactive mode executes each statement after you write it, for instance: >>> x = 1 >>> x += 1 >>> print x 2 >>> y = x * 2 >>> print x, y 2 4 but if you put this in a file: x = 1 x += 1 print x y = x * 2 print x, y then you run your file and it will output: 2 2 4 > because when I run a program in interactive mode, the program run very > good, but if run in not interactive mode not show me error, but the return > of function returns no value, this is the source code: > Your problem isn't that the function returns no value, it's that it doesn't work like you think it should. > def suma(no1,no2): > total=no1+no2 > return total > Right here your function returns the value of "total", not the actual variable. > > print 'hola' > opcion=input() > if opcion==1: > print 'suma' > a=input() > b=input() > suma(a,b) > So right here, the line suma(a, b) does nothing for you, but evaluate the total. If you want to print the value, you need to store it in a variable: total = suma(a, b) would work. > > the result of this code is: > > hola > 1 > suma > 5 > 7 > >>> total > Traceback (most recent call last): > File "<pyshell#0>", line 1, in <module> > total > NameError: name 'total' is not defined > >>> > > why this happens??? what I did wrong??? and why run very good in > interactive mode??? thanks for help me and sorry for my bad english, I from > Mexico and I english student. Thank you. > If you've read the above comments, hopefully that explains what you need. In addition, I re-wrote your program to work properly: def suma(no1, no2): total = no1 + no2 return total print 'Hola' opcion = int(raw_input()) if opcion == 1: print 'Suma' a = int(raw_input()) b = int(raw_input()) total = suma (a, b) print total Hope this helps, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080824/f4ccad49/attachment.htm> From bhaaluu at gmail.com Sun Aug 24 15:18:00 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 24 Aug 2008 09:18:00 -0400 Subject: [Tutor] hi... In-Reply-To: <BLU139-W4598415CA35B55905B631899640@phx.gbl> References: <BLU139-W4598415CA35B55905B631899640@phx.gbl> Message-ID: <ea979d70808240618h665b0fa4l76e4a698f5bcd916@mail.gmail.com> On Sun, Aug 24, 2008 at 2:31 AM, Alberto Perez <betopm at live.com.mx> wrote: > I have a problem with python, I'm begginner in python. How clear the screen > of GUI python interactive???? I'm not sure what you mean by GUI interactive? However, at the Python interactive prompt, I can "clear the screen" using a simple, old-fashioned way: >>> for i in range(1,50): >>> print("\n") That prints 50 newlines, thus effectively "clearing the screen." Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From alan.gauld at btinternet.com Sun Aug 24 16:22:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Aug 2008 15:22:42 +0100 Subject: [Tutor] hi... References: <BLU139-W4598415CA35B55905B631899640@phx.gbl> Message-ID: <g8rqrk$drn$1@ger.gmane.org> "Alberto Perez" <betopm at live.com.mx> wrote >. How clear the screen of GUI python interactive???? bhaaaluu answered that > and which is the difference between interactive mode > and not interactive mode???? WW answered that > because when I run a program in interactive mode, > the program run very good, but if run in not interactive > mode not show me error, How are you running your program in "non interactive mode" Are you using IDLE or Pythonwin? Or are you running it from a command window? If you are running it from IDLE are you creating a new file and typing in the code then saving it and running it from the menu (or F5 key)? That's what it looks like... > but the return of function returns no value It returns a value but you don't print it. One big difference between >>> and non interactive mode is that the >>> prompt prints the values of expressions, including function calls. Non interacticve mode does not print these, you have to use print. (This is why in my tutorial I always use print even in the >>> prompt; because it avoids this confusion.) Thus print suma(a,b) would show the result. Or as WW said you could store the result in a variable called total def suma(no1,no2): total=no1+no2 return total print 'hola' opcion=input() # could replace with: opcion = input("hola\n") if opcion==1: print 'suma' a=input() # its good to give a prompt string of some kind b=input() print suma(a,b) >>> total ... > name 'total' is not defined>>> > > why this happens??? As the error says total is not defined in your shells namespace. It only exists within your program. As WW said, it only exists inside suma() in your code. Thasts why you need to create a "global" level variable or just print the result of suma() directly. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From broek at cc.umanitoba.ca Sun Aug 24 16:24:12 2008 From: broek at cc.umanitoba.ca (broek at cc.umanitoba.ca) Date: Sun, 24 Aug 2008 09:24:12 -0500 Subject: [Tutor] hi... In-Reply-To: <BLU139-W4598415CA35B55905B631899640@phx.gbl> References: <BLU139-W4598415CA35B55905B631899640@phx.gbl> Message-ID: <20080824092412.gko2er1pgkw48c88@webware.cc.umanitoba.ca> ----- Message from betopm at live.com.mx --------- Date: Sun, 24 Aug 2008 01:31:28 -0500 From: Alberto Perez <betopm at live.com.mx> Reply-To: Alberto Perez <betopm at live.com.mx> Subject: [Tutor] hi... To: tutor at python.org > run a program in interactive mode, the program run very good, but if > run in not interactive mode not show me error, but the return of > function returns no value, this is the source code: > > def suma(no1,no2): total=no1+no2 > return total > print 'hola' > opcion=input() > if opcion==1: > print 'suma' > a=input() b=input()> > suma(a,b) > > the result of this code is: > > hola > 1 > suma > 5 > 7 >>> total > Traceback (most recent call last): File "<pyshell#0>", line 1, in > <module> totalNameError: name 'total' is not defined>>> > > why this happens??? what I did wrong??? and why run very good in Hi, Welcome to python and the tutor list. An earlier response pointed out that you need to bind the returned value to total as in > total = suma(a, b) but I thought a bit of explanation might help. In your function, you define total. That makes `total' a name in the scope of the function. That means that `total' can be seen by code in your function, but not code outside of your function. This might seem confusing now, but in the long run, it makes life easier. How? Well, you can define all sorts of names in the body of your functions without having them clutter up the name-space of your overall code. That makes things cleaner. It also makes them less error prone. If total defined in your function was visible everywhere by default, then you would have to make sure that your function didn't define any names that higher level code did. (You'd have to make sure that total defined in a function didn't overwrite total defined outside of the function.) You can make names defined in functions be globally available, but until you've got some experience, don't do that. (Arguably, once you have experience, don't do that then either ;-) Hope that helps some, Brian vdB From 2104496328 at sms.mycricket.com Sun Aug 24 13:33:27 2008 From: 2104496328 at sms.mycricket.com (2104496328 at sms.mycricket.com) Date: 24 Aug 08 05:33:27 -0600 Subject: [Tutor] (no subject) Message-ID: <200808241133.m7O6Yst6027924@mta2-den.mycricket.com> ([Tutor] How do I delete all Files of certain extension type?) --------------------------------------------- Sent by a Cricket mobile device --------------------------------------------- From dotancohen at gmail.com Sun Aug 24 18:08:30 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 24 Aug 2008 19:08:30 +0300 Subject: [Tutor] Including files for security. Message-ID: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com> I have a specific file in the web tree that makes a database call. I am uncomfortable keeping the database username and password in the file. In PHP I usually put the database connection data in a file outside the web tree and use the include (http://il.php.net/include/) function to get the data. Is there a similar mechanism in Python? What do other Python programmers use? Thanks. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From kent37 at tds.net Sun Aug 24 19:24:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Aug 2008 13:24:55 -0400 Subject: [Tutor] Including files for security. In-Reply-To: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com> References: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com> Message-ID: <1c2a2c590808241024sfb5420apb924d1c0755cefc9@mail.gmail.com> On Sun, Aug 24, 2008 at 12:08 PM, Dotan Cohen <dotancohen at gmail.com> wrote: > I have a specific file in the web tree that makes a database call. I > am uncomfortable keeping the database username and password in the > file. In PHP I usually put the database connection data in a file > outside the web tree and use the include (http://il.php.net/include/) > function to get the data. Is there a similar mechanism in Python? What > do other Python programmers use? You can use the normal file open() and read() functions to read the username and password from a file. You can write the file as a Python module, put it somewhere in the Python path and import it. You can use the ConfigParser module to read an INI file... Kent From dotancohen at gmail.com Sun Aug 24 19:41:05 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 24 Aug 2008 20:41:05 +0300 Subject: [Tutor] Including files for security. In-Reply-To: <1c2a2c590808241024sfb5420apb924d1c0755cefc9@mail.gmail.com> References: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com> <1c2a2c590808241024sfb5420apb924d1c0755cefc9@mail.gmail.com> Message-ID: <880dece00808241041j766e8f28l8b2b4dbf296930a6@mail.gmail.com> 2008/8/24 Kent Johnson <kent37 at tds.net>: > On Sun, Aug 24, 2008 at 12:08 PM, Dotan Cohen <dotancohen at gmail.com> wrote: >> I have a specific file in the web tree that makes a database call. I >> am uncomfortable keeping the database username and password in the >> file. In PHP I usually put the database connection data in a file >> outside the web tree and use the include (http://il.php.net/include/) >> function to get the data. Is there a similar mechanism in Python? What >> do other Python programmers use? > > You can use the normal file open() and read() functions to read the > username and password from a file. You can write the file as a Python > module, put it somewhere in the Python path and import it. You can use > the ConfigParser module to read an INI file... > > Kent > I think that I will use the open() and read() functions, thanks! I did think of that, but I wanted to know if there was a better wheel invented already. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From alan.gauld at btinternet.com Sun Aug 24 21:31:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Aug 2008 20:31:08 +0100 Subject: [Tutor] (no subject) References: <200808241133.m7O6Yst6027924@mta2-den.mycricket.com> Message-ID: <g8sctu$4tf$1@ger.gmane.org> <2104496328 at sms.mycricket.com> wrote > ([Tutor] How do I delete all Files of certain extension type?) Get a list of the files - try glob.glob or os.walk Then delete them - use shutil.remove Now if thats not enough info come back with more specific questions. You might find the Using the OS topic in my tutorial helpful. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Aug 24 21:33:26 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Aug 2008 20:33:26 +0100 Subject: [Tutor] Including files for security. References: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com><1c2a2c590808241024sfb5420apb924d1c0755cefc9@mail.gmail.com> <880dece00808241041j766e8f28l8b2b4dbf296930a6@mail.gmail.com> Message-ID: <g8sd28$5cg$1@ger.gmane.org> "Dotan Cohen" <dotancohen at gmail.com> wrote > I think that I will use the open() and read() functions, thanks! I > did > think of that, but I wanted to know if there was a better wheel > invented already. Another option is to use environment variables to store them. These can be set when the server starts up. But a config file is ok too. Alan G. From dotancohen at gmail.com Sun Aug 24 22:38:41 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 24 Aug 2008 23:38:41 +0300 Subject: [Tutor] Including files for security. In-Reply-To: <g8sd28$5cg$1@ger.gmane.org> References: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com> <1c2a2c590808241024sfb5420apb924d1c0755cefc9@mail.gmail.com> <880dece00808241041j766e8f28l8b2b4dbf296930a6@mail.gmail.com> <g8sd28$5cg$1@ger.gmane.org> Message-ID: <880dece00808241338k7704ce28t97b6a4729b9e6c6f@mail.gmail.com> 2008/8/24 Alan Gauld <alan.gauld at btinternet.com>: > > "Dotan Cohen" <dotancohen at gmail.com> wrote > >> I think that I will use the open() and read() functions, thanks! I did >> think of that, but I wanted to know if there was a better wheel >> invented already. > > Another option is to use environment variables to store them. > These can be set when the server starts up. But a config file > is ok too. > Thanks, I will google that. But I will save it for other uses, as I don't want to risk an exploit where one could walk the environment and discover that info. Does Python have an equivalent to phpinfo()? -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From ezra.taylor at gmail.com Mon Aug 25 03:26:37 2008 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Sun, 24 Aug 2008 21:26:37 -0400 Subject: [Tutor] fileinput question Message-ID: <eb90f15e0808241826n2c76af71l1021622d7432f55c@mail.gmail.com> Hello all: Can I do the below with input() from fileinput? If this is not possible, what can I do to create backup files with the date timestamp as an extension. Thanks for you help all. from time import strftime for line in fileinput.input(inplace=1,backup='.strftime("%Y-%b-%d.%S")' do something. -- Ezra Taylor From srilyk at gmail.com Mon Aug 25 03:37:06 2008 From: srilyk at gmail.com (W W) Date: Sun, 24 Aug 2008 20:37:06 -0500 Subject: [Tutor] fileinput question In-Reply-To: <eb90f15e0808241826n2c76af71l1021622d7432f55c@mail.gmail.com> References: <eb90f15e0808241826n2c76af71l1021622d7432f55c@mail.gmail.com> Message-ID: <333efb450808241837g126b1c0an56aae6097f930ae7@mail.gmail.com> On Sun, Aug 24, 2008 at 8:26 PM, Ezra Taylor <ezra.taylor at gmail.com> wrote: > Hello all: > Can I do the below with input() from fileinput? If > this is not possible, what can I do to create backup files with the > date timestamp as an extension. Thanks for you help all. > > > from time import strftime > > for line in fileinput.input(inplace=1,backup='.strftime("%Y-%b-%d.%S")' > do something. > -- > filename = "myfile" + strftime("%Y-%b-%d.%S") + ".txt" f = open(filename, "w") mystring = "This is a file or something" f.write(mystring) f.close() I assume strftime creates a string object so you can concatenate it.... but that should give you what you need (or at least point you in the right direction). -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080824/10e7b002/attachment.htm> From srilyk at gmail.com Mon Aug 25 03:41:18 2008 From: srilyk at gmail.com (W W) Date: Sun, 24 Aug 2008 20:41:18 -0500 Subject: [Tutor] Fwd: Including files for security. In-Reply-To: <333efb450808241840x3b2263f5yfb270ef48c380217@mail.gmail.com> References: <880dece00808240908x739e0341hf5e78ffb48e181c@mail.gmail.com> <1c2a2c590808241024sfb5420apb924d1c0755cefc9@mail.gmail.com> <880dece00808241041j766e8f28l8b2b4dbf296930a6@mail.gmail.com> <g8sd28$5cg$1@ger.gmane.org> <880dece00808241338k7704ce28t97b6a4729b9e6c6f@mail.gmail.com> <333efb450808241840x3b2263f5yfb270ef48c380217@mail.gmail.com> Message-ID: <333efb450808241841r1a8f60a5kee10f68a8f904b37@mail.gmail.com> ---------- Forwarded message ---------- From: W W <srilyk at gmail.com> Date: Sun, Aug 24, 2008 at 8:40 PM Subject: Re: [Tutor] Including files for security. To: Dotan Cohen <dotancohen at gmail.com> On Sun, Aug 24, 2008 at 3:38 PM, Dotan Cohen <dotancohen at gmail.com> wrote: > 2008/8/24 Alan Gauld <alan.gauld at btinternet.com>: > > > > "Dotan Cohen" <dotancohen at gmail.com> wrote > > > >> I think that I will use the open() and read() functions, thanks! I did > >> think of that, but I wanted to know if there was a better wheel > >> invented already. > > > > Another option is to use environment variables to store them. > > These can be set when the server starts up. But a config file > > is ok too. > > > > Thanks, I will google that. But I will save it for other uses, as I > don't want to risk an exploit where one could walk the environment and > discover that info. Does Python have an equivalent to phpinfo()? > You could also store the passwords as a salted hash, and use a nondescript method to import/decode them. It wouldn't stop the serious attacker, but it would make it a little harder for accidental discovery. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080824/bea10478/attachment-0001.htm> From kent37 at tds.net Mon Aug 25 04:33:25 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Aug 2008 22:33:25 -0400 Subject: [Tutor] fileinput question In-Reply-To: <eb90f15e0808241826n2c76af71l1021622d7432f55c@mail.gmail.com> References: <eb90f15e0808241826n2c76af71l1021622d7432f55c@mail.gmail.com> Message-ID: <1c2a2c590808241933t7ded0c68h365582ce8e718770@mail.gmail.com> On Sun, Aug 24, 2008 at 9:26 PM, Ezra Taylor <ezra.taylor at gmail.com> wrote: > Hello all: > Can I do the below with input() from fileinput? If > this is not possible, what can I do to create backup files with the > date timestamp as an extension. Thanks for you help all. > > > from time import strftime > > for line in fileinput.input(inplace=1,backup='.strftime("%Y-%b-%d.%S")' Close, but not quite. strftime() won't be recognized in a string, but you can include the leading period in the format string. Try fileinput.input(inplace=1,backup=strftime(".%Y-%b-%d.%S") Kent From ezra.taylor at gmail.com Mon Aug 25 05:15:00 2008 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Sun, 24 Aug 2008 23:15:00 -0400 Subject: [Tutor] fileinput question In-Reply-To: <1c2a2c590808241933t7ded0c68h365582ce8e718770@mail.gmail.com> References: <eb90f15e0808241826n2c76af71l1021622d7432f55c@mail.gmail.com> <1c2a2c590808241933t7ded0c68h365582ce8e718770@mail.gmail.com> Message-ID: <eb90f15e0808242015j7a7bc57blcd3fbeed9e134f31@mail.gmail.com> Thanks Kent, that works. On Sun, Aug 24, 2008 at 10:33 PM, Kent Johnson <kent37 at tds.net> wrote: > On Sun, Aug 24, 2008 at 9:26 PM, Ezra Taylor <ezra.taylor at gmail.com> wrote: >> Hello all: >> Can I do the below with input() from fileinput? If >> this is not possible, what can I do to create backup files with the >> date timestamp as an extension. Thanks for you help all. >> >> >> from time import strftime >> >> for line in fileinput.input(inplace=1,backup='.strftime("%Y-%b-%d.%S")' > > Close, but not quite. strftime() won't be recognized in a string, but > you can include the leading period in the format string. Try > fileinput.input(inplace=1,backup=strftime(".%Y-%b-%d.%S") > > Kent > -- Ezra Taylor From eric at ericabrahamsen.net Mon Aug 25 05:49:10 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 25 Aug 2008 11:49:10 +0800 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> Message-ID: <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> On Aug 24, 2008, at 7:20 PM, Kent Johnson wrote: > Forwarding to the list with my reply. Please use Reply All to reply > to the list. Grr, sorry, I keep forgetting... > > > On Sun, Aug 24, 2008 at 1:02 AM, Eric Abrahamsen > <eric at ericabrahamsen.net> wrote: >> >> On Aug 23, 2008, at 11:22 PM, Kent Johnson wrote: >> >>> On Sat, Aug 23, 2008 at 6:47 AM, Eric Abrahamsen >>> <eric at ericabrahamsen.net> wrote: >>>> >>>> At first I thought the bisect module was the way to go, but it is >>>> too >>>> tightly tied to integer list indices, and works very awkwardly when >>>> bisecting on datetime attributes. >>> >>> I'm not sure what the problem is with bisect (to find the starting >>> point). Your list of model elements has integer indices. I think you >>> have to write a __cmp__ method for your model class that compares on >>> the datetime attribute, then it should work. You can also create a >>> list of (key, model) and sort/search that. >>> http://www.mail-archive.com/python-list at python.org/msg189443.html >> >> The __cmp__ trick is very nice, and would do it, except I won't >> have access >> to the events model classes. I could get bisect to work by feeding >> it a list >> comprehension, but making the high and low parameters work required >> integer >> indices, which seemed like one half-hack too many... > > I don't understand the issue. *All* lists have integer indices. If you > make a list of (key, model) pairs, the keys only need to be > comparable, not integers. The main problem is that I don't have any control over the list of models, and all I've got is the name of a datetime attribute to filter by. The only way I could get bisect to work was like this: index = bisect([getattr(x, attr_name) for x in model_list], sentinel_date) But that loops over the whole list, which is what I was trying to avoid. And the only way I could provide high and low parameters to bisect is by calling event_list.index(event), which doesn't work on django querysets. I also experimented with itertools.groupby to produce groups of events, but that turned out to be far slower than simply looping over the whole event list and extracting events which test true for c.start <= getattr(event, attr_name) < c.stop. Ideally I could create a kind of concurrent iterator, that steps through children's blocks of time and the object's event list in tandem, rather than going over the whole events list once for every child produced. Maybe that's not possible... I'm pasting the whole function down below, just for the hell of it. Thanks again, Eric def _iter_children(self, child, require_events=False): """ Iterate through an object's 'child' items. If require_events == True, only return children with events, otherwise return all children. """ while self.sentinel < self.stop: c = child([], self.sentinel, self.start_attr, rolling=self.rolling, counts_only=self.counts_only) for e in self.events: if c.start <= getattr(e,self.start_attr) < c.stop: c.events.append(e) self.sentinel += c.dt_range if not require_events or c.has_events(): yield c From xboxmuncher at gmail.com Mon Aug 25 06:57:21 2008 From: xboxmuncher at gmail.com (xbmuncher) Date: Mon, 25 Aug 2008 00:57:21 -0400 Subject: [Tutor] Read active tab url from firefox Message-ID: <df531c470808242157k758c4fb6ta5b6d857d9d809ea@mail.gmail.com> I want to make a program in python that knows the current url of the active tab in firefox. I want to be able to right click anywhere in my system, notepad, firefox..etc.. and be able to see an added menu option. Any pointers on doing this? Summary of goals: 1. retrieve url of current tab from firefox 2. add right click option that displays anywhere I right click the mouse in windows xp, notepad, a browser, desktop..wherever 3. maybe I want to activate an action in windows when I press some key combinations.. how can I do this with python? -thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080825/de4097bf/attachment.htm> From dsarmientos at gmail.com Mon Aug 25 07:47:04 2008 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Mon, 25 Aug 2008 00:47:04 -0500 Subject: [Tutor] Graphically Display Binary Trees In-Reply-To: <1c2a2c590808231408r43df4d8fq69b4774407a19f3f@mail.gmail.com> References: <d356a5240808231334o2f2a4428we4da48eb59cad585@mail.gmail.com> <1c2a2c590808231408r43df4d8fq69b4774407a19f3f@mail.gmail.com> Message-ID: <d356a5240808242247y6d7db54fu84f7216d0c5a0a4e@mail.gmail.com> Thank you for your suggestions, I created a working prototype now, http://dpaste.com/73630/ Daniel > On Sat, Aug 23, 2008 at 4:08 PM, Kent Johnson <kent37 at tds.net> wrote: > Graphviz's dot is an amazing way to produce graphics from graph data. > pydot can produce the dot files needed to create the graphics. > http://code.google.com/p/pydot/ > > Kent > From alan.gauld at btinternet.com Mon Aug 25 11:10:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Aug 2008 10:10:01 +0100 Subject: [Tutor] Read active tab url from firefox References: <df531c470808242157k758c4fb6ta5b6d857d9d809ea@mail.gmail.com> Message-ID: <g8tstb$pq1$1@ger.gmane.org> "xbmuncher" <xboxmuncher at gmail.com> wrote >I want to make a program in python that knows the current url of the >active > tab in firefox. I want to be able to right click anywhere in my > system, > notepad, firefox..etc.. and be able to see an added menu option. > Any pointers on doing this? This is impossible, sorry. You can get some of it to work, you might even get all of it to work some of the time, but you can't get all of it to work all of the time. You simply don't have that much control, nor should you! > Summary of goals: > 1. retrieve url of current tab from firefox That should be possible with some deep digging into the internals of FireFox's COM model or, if necessary, into its window tree. > 2. add right click option that displays anywhere I right click the > mouse in > windows xp, notepad, a browser, desktop..wherever This is the tricky bit. Every program has the option of creating its own right-click menu and it may not expose that in such a way that you can add items to it. Some older Windows apps draw their own right click menus bypassing the Windows widget set and for those you have no chance (or if you do you will likely destroy the apps own menu system!). Even for those that use the standard Windows mechanisms it might be tricky. I think you will need to monitor the running task list and every time a new task starts your code will have to attach its menu item to that application. Even then things like X windows under cygwin has its own menuing system quite separate to Windows and I doubt it will be possible there without also writing a cygwin/X version of your code. Messing around with other people's applications is tricky and trying to do it in a generic way is trickier still. > 3. maybe I want to activate an action in windows when I press some > key > combinations.. how can I do this with python? This could be standard windows hot-key functionality. You can assign hot keys in windows to bring up applications via the properrties/shortcut dialog. I don't kow your level of skill with Windows programming or Python but this may be a lot harder than you think. Its certainly not a project I'd recommend for a beginner in Python. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From lie.1296 at gmail.com Mon Aug 25 12:10:09 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 25 Aug 2008 17:10:09 +0700 Subject: [Tutor] Python open of c:\ path Problem In-Reply-To: <mailman.43.1219572018.11867.tutor@python.org> References: <mailman.43.1219572018.11867.tutor@python.org> Message-ID: <1219659009.15589.13.camel@lieryan-laptop> > Message: 7 > Date: Sun, 24 Aug 2008 00:21:45 +0100 > From: "Alan Gauld" <alan.gauld at btinternet.com> > Subject: Re: [Tutor] Python open of c:\ path Problem > To: tutor at python.org > Message-ID: <g8q62a$msi$1 at ger.gmane.org> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote > > > junkfile = open('c:\tmp\junkpythonfile','w') > > IOError: [Errno 2] No such file or directory: > > 'c:\tmp\\junkpythonfile' > > > > I suspect the problem is with the back slash. Comments? > > Correct. There are several ways round this, the simplest > being to use forward slashes which are effectively portable > across most OSs. > > junkfile = open('c:/tmp/junkpythonfile','w') > > You could use a raw string by prefixing the string with r > > junkfile = open(r'c:\tmp\junkpythonfile','w') > > > Or you could escape the backslash > > junkfile = open('c:\\tmp\\junkpythonfile','w') > > > BTW, how does one continue a long statement > > that has, say, a long path to a file? > > You can create a long string by adding the shorter string > elements : > > f = open( > "a:/very/long/path/name/that/needs/a/whole/line/to./itself.py", > "w") > > becomes > > f = open("a:/very/long/path/name/" + > "that/needs/a/whole/" + > "line/to./itself.py","w") > > > or by using a line continuation character. > > f = open("a:/very/long/path/name/" \ > "that/needs/a/whole/" \ > "line/to./itself.py", "w") > You don't even need the line continuation character, you can use implicit line continuation character (since it's inside a parentheses) f = open("a:/very/long/path/name/" "that/needs/a/whole/" "line/to./itself.py", "w") > HTH, > From eric at ericabrahamsen.net Mon Aug 25 16:16:36 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 25 Aug 2008 22:16:36 +0800 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> Message-ID: <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> Okay I think I'm onto something, more iterator-related stuff. If I can make self.events an iterator, then run a for loop on it, breaking out of the loop when the events' date attributes get too high. Then on the next run through, that same for loop should pick up where it left off, right? Here's my next version of the function. It doesn't quite work right: when I test it each child instance receives the correct events, but when it passes those events onto its children, they get consumed (or something) and are never actually output. To test I'm instantiating a Month m, filling it with events, then looping like so: for w in m: print w.event_count() for d in w: print d.events w.event_count() produces the right event count, but d.events is always empty. If anyone can see what's wrong with this function... ###### def _iter_children(self, child, require_events=False): """ Iterate through an object's 'child' items. If require_events == True, only return children with events, otherwise return all children. """ iterevents = iter(self.events) while self.sentinel < self.stop: c = child([], self.sentinel, self.start_attr, rolling=self.rolling, counts_only=self.counts_only) for e in iterevents: if getattr(e, self.start_attr) < c.stop: c.events.append(e) else: break self.sentinel += c.dt_range if not require_events or c.has_events(): # if require_events == True, omit empty children. yield c On Aug 25, 2008, at 11:49 AM, Eric Abrahamsen wrote: > > On Aug 24, 2008, at 7:20 PM, Kent Johnson wrote: > >> Forwarding to the list with my reply. Please use Reply All to reply >> to the list. > > Grr, sorry, I keep forgetting... > >> >> >> On Sun, Aug 24, 2008 at 1:02 AM, Eric Abrahamsen >> <eric at ericabrahamsen.net> wrote: >>> >>> On Aug 23, 2008, at 11:22 PM, Kent Johnson wrote: >>> >>>> On Sat, Aug 23, 2008 at 6:47 AM, Eric Abrahamsen >>>> <eric at ericabrahamsen.net> wrote: >>>>> >>>>> At first I thought the bisect module was the way to go, but it >>>>> is too >>>>> tightly tied to integer list indices, and works very awkwardly >>>>> when >>>>> bisecting on datetime attributes. >>>> >>>> I'm not sure what the problem is with bisect (to find the starting >>>> point). Your list of model elements has integer indices. I think >>>> you >>>> have to write a __cmp__ method for your model class that compares >>>> on >>>> the datetime attribute, then it should work. You can also create a >>>> list of (key, model) and sort/search that. >>>> http://www.mail-archive.com/python-list at python.org/msg189443.html >>> >>> The __cmp__ trick is very nice, and would do it, except I won't >>> have access >>> to the events model classes. I could get bisect to work by feeding >>> it a list >>> comprehension, but making the high and low parameters work >>> required integer >>> indices, which seemed like one half-hack too many... >> >> I don't understand the issue. *All* lists have integer indices. If >> you >> make a list of (key, model) pairs, the keys only need to be >> comparable, not integers. > > The main problem is that I don't have any control over the list of > models, and all I've got is the name of a datetime attribute to > filter by. The only way I could get bisect to work was like this: > > index = bisect([getattr(x, attr_name) for x in model_list], > sentinel_date) > > But that loops over the whole list, which is what I was trying to > avoid. And the only way I could provide high and low parameters to > bisect is by calling event_list.index(event), which doesn't work on > django querysets. I also experimented with itertools.groupby to > produce groups of events, but that turned out to be far slower than > simply looping over the whole event list and extracting events which > test true for c.start <= getattr(event, attr_name) < c.stop. > > Ideally I could create a kind of concurrent iterator, that steps > through children's blocks of time and the object's event list in > tandem, rather than going over the whole events list once for every > child produced. Maybe that's not possible... I'm pasting the whole > function down below, just for the hell of it. > > Thanks again, > Eric > > > def _iter_children(self, child, require_events=False): > """ > Iterate through an object's 'child' items. > > If require_events == True, only return children with > events, otherwise return all children. > """ > while self.sentinel < self.stop: > c = child([], self.sentinel, self.start_attr, > rolling=self.rolling, counts_only=self.counts_only) > for e in self.events: > if c.start <= getattr(e,self.start_attr) < c.stop: > c.events.append(e) > self.sentinel += c.dt_range > if not require_events or c.has_events(): > yield c > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Mon Aug 25 19:12:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Aug 2008 13:12:10 -0400 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> Message-ID: <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> I'm not following your code very well. I don't understand the relationship between the first loop and the iter_children() function. A couple of things that might help: - Django QuerySets can be qualified with additional tests, so you could have each of your month/week/etc classes have its own correctly qualified QuerySet. This will result in one database query for each event class, and multiple copies of the actual events. - When you start iterating a QuerySet, it fetches all the model instances into a list. I think you are trying to use iterators to prevent this fetch but Django doesnt' work that way. You might as well just use the list. - Iterators can't be restarted, I think that is why your latest iter_children() doesn't work as you expect. Can you say some more about why you are doing this? Where do all the initial constraints come from? Do you really have to be so careful to protect against a 'madman' user? Perhaps you could set a limit on the number of events you will retrieve and use a count() on the QuerySet to ensure that not too many records have been fetched. Maybe you should try a straightforward implementation and when you have something working you can worry about making it better. Kent From deliberatus at verizon.net Mon Aug 25 18:18:48 2008 From: deliberatus at verizon.net (Kirk Bailey) Date: Mon, 25 Aug 2008 12:18:48 -0400 Subject: [Tutor] editmypage Message-ID: <48B2DB68.5070508@verizon.net> I wrote a password protected program to edit webpages via http. thiss iss in 2 files, one serves the editing page, one saves the edited page and shows the rssults. http://www.freeholdmarketing.com/EditMyPage.py http://www.freeholdmarketing.com/EditMyPage2.py This take a link on the page to edit. This can be a universal link by using server side includes such as: ><a href="/cgi-bin/EditMyPage.py?<!--#echo var="DOCUMENT_URI" -->">Edit this page</a> Just a hack to make my life a little simpler. It is free, feel free to rip me off. -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From deliberatus at verizon.net Mon Aug 25 18:47:03 2008 From: deliberatus at verizon.net (Kirk Bailey) Date: Mon, 25 Aug 2008 12:47:03 -0400 Subject: [Tutor] test Message-ID: <48B2E207.9080900@verizon.net> is my posting getting through? -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From kent37 at tds.net Mon Aug 25 19:59:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Aug 2008 13:59:27 -0400 Subject: [Tutor] editmypage In-Reply-To: <48B2DB68.5070508@verizon.net> References: <48B2DB68.5070508@verizon.net> Message-ID: <1c2a2c590808251059v7f89c51bi39ffcbd257560796@mail.gmail.com> On Mon, Aug 25, 2008 at 12:18 PM, Kirk Bailey <deliberatus at verizon.net> wrote: > I wrote a password protected program to edit webpages via http. thiss iss in > 2 files, one serves the editing page, one saves the edited page and shows > the rssults. > http://www.freeholdmarketing.com/EditMyPage.py > http://www.freeholdmarketing.com/EditMyPage2.py You might want to look into wikis like MoinMoin or Trac... Kent From srilyk at gmail.com Mon Aug 25 21:11:41 2008 From: srilyk at gmail.com (W W) Date: Mon, 25 Aug 2008 14:11:41 -0500 Subject: [Tutor] test In-Reply-To: <48B2E207.9080900@verizon.net> References: <48B2E207.9080900@verizon.net> Message-ID: <333efb450808251211n60c9ec3fva5172a8464a20026@mail.gmail.com> yup On Mon, Aug 25, 2008 at 11:47 AM, Kirk Bailey <deliberatus at verizon.net>wrote: > is my posting getting through? > -- > > > Cheers! > -Kirk D Bailey > > THINK > +-----+ > .*. | BOX | > ..* +-----+ > *** THINK > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080825/6cd5e777/attachment.htm> From bermanrl at embarqmail.com Mon Aug 25 22:39:46 2008 From: bermanrl at embarqmail.com (Robert Berman) Date: Mon, 25 Aug 2008 16:39:46 -0400 Subject: [Tutor] test In-Reply-To: <48B2E207.9080900@verizon.net> References: <48B2E207.9080900@verizon.net> Message-ID: <48B31892.9000805@embarqmail.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080825/fd347f84/attachment-0001.htm> From ricaraoz at gmail.com Mon Aug 25 14:39:38 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 25 Aug 2008 09:39:38 -0300 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <g8mv4r$7vl$1@ger.gmane.org> References: <mailman.21167.1219397347.920.tutor@python.org> <1219425152.6882.58.camel@lieryan-laptop> <g8mv4r$7vl$1@ger.gmane.org> Message-ID: <48B2A80A.6050400@bigfoot.com> Emile van Sebille wrote: > Lie Ryan wrote: >> >> In a much simpler situation, even a communicating from a plain file >> could be enough. In the daemon's program folder, there'll be two files: >> input and output. You write to input to instruct the server and read the >> response from output. This model is in respect to Unix's philosophy: >> "make program to handle text streams, because it's the universal >> interface". >> > > I've done this and it works well... one thing to watch out for though is > snagging a file before it's completely written. Setting up a semaphore > or pausing to allow the file write to complete once seeing the file > fixes it adequately. > If instead of an input/output file you use a directory this is easily solved. You write your request to a uniquely named file (with .in extension) and you read the response out of an equally named file with a .out extension. The server polls the directory for new .in files and processes them in order of creation date (you can even include a priorities scheme coded in the extension (e.g. .in1 to .in9 for the different priorities). From ricaraoz at gmail.com Mon Aug 25 16:43:07 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 25 Aug 2008 11:43:07 -0300 Subject: [Tutor] Python Docs (Was: Reformatting phone number) In-Reply-To: <1c2a2c590808230805j35f220ekd03738148922ccef@mail.gmail.com> References: <880dece00808210901m3b33883m50b39a6728d3065b@mail.gmail.com> <16651e80808211129u5ad6c273t13750d6ba7e94d01@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D035B7056@csomb01.corp.atmel.com> <48AEC347.4020402@bigfoot.com> <1c2a2c590808230805j35f220ekd03738148922ccef@mail.gmail.com> Message-ID: <48B2C4FB.7090904@bigfoot.com> Kent Johnson wrote: > On Fri, Aug 22, 2008 at 9:46 AM, Ricardo Ar?oz <ricaraoz at gmail.com> wrote: > >> What I find lacking in the docs are a link to a code example for every item >> and a "See Also" link to other related items. With some modules I can't make >> sense of the different bits and pieces till I see a code example, and I >> think this would be the greatest improvement to the actually very good docs. > > You might like Doug Hellman's Python Module of the Week pages. He > gives exhaustive examples of each module. > http://www.doughellmann.com/projects/PyMOTW/ > > Kent > Thanks Kent, yes, I knew the place. I didn't mean to say that I "couldn't" find code examples, after all google's my friend ;c). But I might also google for everything that I can find in the docs. What I meant is that the docs could be immensely improved by providing code examples IN them. From emile at fenx.com Tue Aug 26 01:58:40 2008 From: emile at fenx.com (Emile van Sebille) Date: Mon, 25 Aug 2008 16:58:40 -0700 Subject: [Tutor] pass argument into running program *outside* of program In-Reply-To: <48B2A80A.6050400@bigfoot.com> References: <mailman.21167.1219397347.920.tutor@python.org> <1219425152.6882.58.camel@lieryan-laptop> <g8mv4r$7vl$1@ger.gmane.org> <48B2A80A.6050400@bigfoot.com> Message-ID: <g8vgvn$o15$1@ger.gmane.org> Ricardo Ar?oz wrote: > Emile van Sebille wrote: >> I've done this and it works well... one thing to watch out for though >> is snagging a file before it's completely written. Setting up a >> semaphore or pausing to allow the file write to complete once seeing >> the file fixes it adequately. >> > > If instead of an input/output file you use a directory this is easily > solved. You write your request to a uniquely named file (with .in > extension) But that doesn't solve the problem. If you have a lot of data to be written to the '.in' file you need to wait for the file writes to complete before reading the contents on the 'other' side. File existence isn't sufficient. Perhaps writing to a '.tmp' and renaming it to '.in' after completely written might do it without the possibility of consuming the partial file before it's ready. Emile From pyhex at yahoo.com Tue Aug 26 02:45:05 2008 From: pyhex at yahoo.com (Py Hex) Date: Mon, 25 Aug 2008 17:45:05 -0700 (PDT) Subject: [Tutor] Why does the Hex builtin function in Python return a string ? Message-ID: <978381.61844.qm@web59603.mail.ac4.yahoo.com> When I run this: >>> type(hex(12)) <type 'str'> I get a string type back, i.e, '0xC' not 0xC On the other hand, if I use 0x with data, Python understands it is hex data and not a string value. >>> e = 0xCD >>> type(e) <type 'int'> Why does the Hex builtin function in Python return a string ? How can I convert this string returned by hex builtin function to data with 0x prefixed ? Am I missing anything ? Is there a builtin in Python (I'm using Python 2.5) that does this conversion from int to hex without returning a string value? It is a bit confusing. Thanks Ramses From srilyk at gmail.com Tue Aug 26 03:13:50 2008 From: srilyk at gmail.com (W W) Date: Mon, 25 Aug 2008 20:13:50 -0500 Subject: [Tutor] Fwd: Why does the Hex builtin function in Python return a string ? In-Reply-To: <333efb450808251807v8257fe5wa2c8a3006166d577@mail.gmail.com> References: <978381.61844.qm@web59603.mail.ac4.yahoo.com> <333efb450808251807v8257fe5wa2c8a3006166d577@mail.gmail.com> Message-ID: <333efb450808251813k4986ac5cm52042f46d46bf347@mail.gmail.com> Forgot to send to list... On Mon, Aug 25, 2008 at 7:45 PM, Py Hex <pyhex at yahoo.com> wrote: > When I run this: > > >>> type(hex(12)) > <type 'str'> > > I get a string type back, i.e, '0xC' not 0xC > > On the other hand, if I use 0x with data, Python understands it is hex data > and not a string value. > > >>> e = 0xCD > >>> type(e) > <type 'int'> You missed trying something: >>> e = 0xCD >>> e 205 >>> type(e) <type 'int'> It doesn't store the value as hex data, it stores it as an integer. I'm really not sure about anything else (i.e. converting the value to an integer - I've tried and int(e) doesn't work when it's a hex string) though. HTH, Wayne p.s. After a quick Google, I discovered how to convert the other way: int('0xCD', 0) will give you the integer value of your string (if it's hex. If you're doing octal you'll want int(myOctal, 8) ) -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080825/56b416d2/attachment.htm> From john at fouhy.net Tue Aug 26 03:18:16 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 26 Aug 2008 13:18:16 +1200 Subject: [Tutor] Why does the Hex builtin function in Python return a string ? In-Reply-To: <978381.61844.qm@web59603.mail.ac4.yahoo.com> References: <978381.61844.qm@web59603.mail.ac4.yahoo.com> Message-ID: <5e58f2e40808251818o41f4deb9x3fad9365810e0c4@mail.gmail.com> 2008/8/26 Py Hex <pyhex at yahoo.com>: > When I run this: > >>>> type(hex(12)) > <type 'str'> > > I get a string type back, i.e, '0xC' not 0xC > > On the other hand, if I use 0x with data, Python understands it is hex data and not a string value. > >>>> e = 0xCD >>>> type(e) > <type 'int'> > > Why does the Hex builtin function in Python return a string ? How can I convert this string returned by hex builtin function to data with 0x prefixed ? If you type 0xC, you get a number. Try it: >>> 0xC 12 '12' is the default python representation of the integer 0xC. Internally, it is (I guess) stored as a 4 byte chunk of memory; that is, a 32-bit long binary. There is _no difference_ between 0xC and 12: >>> 0xC is 12 True The hex() function (and oct() too) provides you with a different string representation from the default. If you want to change python to display integers in hex instead of decimal by default, I can't help you.. (well, maybe you could subclass int, and change __repr__ and __str__ to return hex strings) -- John. From john at fouhy.net Tue Aug 26 03:27:14 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 26 Aug 2008 13:27:14 +1200 Subject: [Tutor] Why does the Hex builtin function in Python return a string ? In-Reply-To: <5e58f2e40808251818o41f4deb9x3fad9365810e0c4@mail.gmail.com> References: <978381.61844.qm@web59603.mail.ac4.yahoo.com> <5e58f2e40808251818o41f4deb9x3fad9365810e0c4@mail.gmail.com> Message-ID: <5e58f2e40808251827r4f50754fgf2b40ec8817f83eb@mail.gmail.com> 2008/8/26 John Fouhy <john at fouhy.net>: > The hex() function (and oct() too) provides you with a different > string representation from the default. If you want to change python > to display integers in hex instead of decimal by default, I can't help > you.. (well, maybe you could subclass int, and change __repr__ and > __str__ to return hex strings) Actually, that was easier than I thought: class HexInt(int): def __repr__(self): return hex(self) def __str__(self): return str(self) def __add__(self, other): return HexInt(int(self)+int(other)) def __sub__(self, other): return HexInt(int(self)-int(other)) def __mul__(self, other): return HexInt(int(self)*int(other)) def __div__(self, other): return HexInt(int(self)/int(other)) >>> h1 = HexInt(13) >>> h2 = HexInt(21) >>> h1, h2 (0xd, 0x15) >>> h1+h2 0x22 >>> h1-h2 -0x8 >>> h1*h2 0x111 >>> int(h1*h2) 273 >>> h1+16 0x1d Of course, there's obvious problems if you want to mix this with floats :-/ And I'm not sure what you'd gain, since as mentioned, integers are integers, whatever they look like. -- John. From kent37 at tds.net Tue Aug 26 03:31:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Aug 2008 21:31:20 -0400 Subject: [Tutor] Why does the Hex builtin function in Python return a string ? In-Reply-To: <978381.61844.qm@web59603.mail.ac4.yahoo.com> References: <978381.61844.qm@web59603.mail.ac4.yahoo.com> Message-ID: <1c2a2c590808251831k4b46a534i13dfc56dfce40f06@mail.gmail.com> On Mon, Aug 25, 2008 at 8:45 PM, Py Hex <pyhex at yahoo.com> wrote: > When I run this: > >>>> type(hex(12)) > <type 'str'> > > I get a string type back, i.e, '0xC' not 0xC > > On the other hand, if I use 0x with data, Python understands it is hex data and not a string value. > >>>> e = 0xCD >>>> type(e) > <type 'int'> > > Why does the Hex builtin function in Python return a string ? How can I convert this string returned by hex builtin function to data with 0x prefixed ? I think you are confusing representation with value. 0xCD and 205 are different representations of the same value. The interpreter understands both but the values are the same. In fact if you ask Python for the value of e in your example, it will say it is 205. The base (10 or 16) is a property of the representation, not the value. The hex() function gives you the string representation of the value as a (base 16) hex string. The str() function gives the standard (base 10) string representation of an integer. Are you just curious or is there something specific you are trying to do? Kent From eric at ericabrahamsen.net Tue Aug 26 07:36:40 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Tue, 26 Aug 2008 13:36:40 +0800 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> Message-ID: <83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net> I do apologize for the large quantities of confusing description ? articulating the problem here has helped me understand exactly what it is I'm after (though it hasn't improved my code!), and I've got a better grasp of the problem now than I did when I first asked. It isn't so much that I need to protect against crazy users, but that the pattern I'm making is very flexible, and could be used in vastly different ways. I want to make sure that it operates on efficient principles, so that people will get the best performance out of it no matter how they use it. So my test case: a Month has a 'child' attribute pointing at Week, which has a 'child' attribute pointing at Day, so they all know what kind of child instances iteration should produce. With nested loops, a Month produces one Week, that Week produces seven Days, then the next Week is produced, it makes seven more Days, etc. That much is easy. Then there's self.events. My original code looped over all of self.events for each child produced. A Month loops over its events four times, a Week seven times. This was the straightforward implementation, but it seemed inefficient. (I also, as you point out, might have been wrong about the way django QuerySets work). My thought was that only one loop over self.events should be necessary, in theory, since they're sorted by date. A for loop creates an iterator from a sequence and calls next() on it, and it creates an entirely new iterator each time you start a new for loop: each for loop starts from the beginning of the sequence. But if you create your own iterator from the sequence and run a for loop on it, then using break to jump out of the for loop should leave the iterator just where you left it, since it maintains state. Doing another for loop on it (the next time through the date-based while loop), should pick up where it left off. That's why the line "iterevents = iter(self.events)" is outside of the while loop: it is only created once, and the loops later in the function all make use of the same iterator, instead of creating a new one every time. I'm pretty sure this works in theory, because calling event_count() on the Weeks as they come out returns the correct number of events. But, for some reason, those events are not making it into the Day children. I had originally assumed that a QuerySet pulled objects out of the database in a rolling fashion ? ie iterating on a Month would first draw a Week's worth of events from the database, then another Week, then two more. But if it loads them all at first access, then I might as well just call list() on the QuerySet at object instantiation, and save myself some trouble. I hope that's a little clearer. My central issue is maintaining my place in the self.events loop, and only advancing it as far as the date-based while loop advances. Whether that's possible or not... Thanks again, Eric On Aug 26, 2008, at 1:12 AM, Kent Johnson wrote: > I'm not following your code very well. I don't understand the > relationship between the first loop and the iter_children() function. > > A couple of things that might help: > - Django QuerySets can be qualified with additional tests, so you > could have each of your month/week/etc classes have its own correctly > qualified QuerySet. This will result in one database query for each > event class, and multiple copies of the actual events. > - When you start iterating a QuerySet, it fetches all the model > instances into a list. I think you are trying to use iterators to > prevent this fetch but Django doesnt' work that way. You might as well > just use the list. > - Iterators can't be restarted, I think that is why your latest > iter_children() doesn't work as you expect. > > Can you say some more about why you are doing this? Where do all the > initial constraints come from? Do you really have to be so careful to > protect against a 'madman' user? Perhaps you could set a limit on the > number of events you will retrieve and use a count() on the QuerySet > to ensure that not too many records have been fetched. Maybe you > should try a straightforward implementation and when you have > something working you can worry about making it better. > > Kent From andreengels at gmail.com Tue Aug 26 10:40:42 2008 From: andreengels at gmail.com (Andre Engels) Date: Tue, 26 Aug 2008 10:40:42 +0200 Subject: [Tutor] Python installing in root Message-ID: <6faf39c90808260140v3bb8437h25cd73e3a4f117b2@mail.gmail.com> I am installing Python 2.5 using the Windows installer (running Vista). On my private computer this works as it should, but on my work computer, it installs in the root directory of C: whatever directory I specify it to be installed into. Is this a known problem, and does anybody know what to do about it? -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Tue Aug 26 13:20:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 26 Aug 2008 07:20:41 -0400 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> <83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net> Message-ID: <1c2a2c590808260420k5c7c56d6y25450bad33dd0e2c@mail.gmail.com> On Tue, Aug 26, 2008 at 1:36 AM, Eric Abrahamsen <eric at ericabrahamsen.net> wrote: > So my test case: a Month has a 'child' attribute pointing at Week, which has > a 'child' attribute pointing at Day, so they all know what kind of child > instances iteration should produce. With nested loops, a Month produces one > Week, that Week produces seven Days, then the next Week is produced, it > makes seven more Days, etc. That much is easy. If all you want to do with the nested Month, etc is to iterate the events in them, you could probably use a shared iterator. It would have to be able to push-back items so that when you hit the out-of-range item you could push it back on the iterator. > Then there's self.events. My original code looped over all of self.events > for each child produced. A Month loops over its events four times, a Week > seven times. This was the straightforward implementation, but it seemed > inefficient. (I also, as you point out, might have been wrong about the way > django QuerySets work). My thought was that only one loop over self.events > should be necessary, in theory, since they're sorted by date. Instead of direct use of the list iterator, you could pass the list and the starting index around. Then you don't have to keep finding your place. > A for loop creates an iterator from a sequence and calls next() on it, and > it creates an entirely new iterator each time you start a new for loop: I still don't understand your code but you may have another misconception. Calling iter() on an iterator returns the same iterator; it does not make a new iterator that holds the same place. You can use itertools.tee() to split an iterator if that is what you want to do. Kent From lie.1296 at gmail.com Tue Aug 26 14:44:52 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 26 Aug 2008 19:44:52 +0700 Subject: [Tutor] Python installing in root In-Reply-To: <mailman.55.1219744826.809.tutor@python.org> References: <mailman.55.1219744826.809.tutor@python.org> Message-ID: <1219754693.15589.35.camel@lieryan-laptop> On Tue, 2008-08-26 at 12:00 +0200, tutor-request at python.org wrote: > > > Message: 2 > Date: Tue, 26 Aug 2008 10:40:42 +0200 > From: "Andre Engels" <andreengels at gmail.com> > Subject: [Tutor] Python installing in root > To: "Python Tutor List" <tutor at python.org> > Message-ID: > <6faf39c90808260140v3bb8437h25cd73e3a4f117b2 at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > I am installing Python 2.5 using the Windows installer (running > Vista). On my private computer this works as it should, but on my work > computer, it installs in the root directory of C: whatever directory I > specify it to be installed into. Is this a known problem, and does > anybody know what to do about it? > > -- > Andr? Engels, andreengels at gmail.com I have installed Python 2.5 on Windows Vista (Home Basic) on C:\Program Files, so clearly this is not a global problem. My guess is that at the work computer, you don't have write access to the directory you're installing python to, so the installer defaults to the root C:\ (for some odd reason, it's quite unusual to have access to root C:\ but not <insert any other directory here>). From andreengels at gmail.com Tue Aug 26 15:05:41 2008 From: andreengels at gmail.com (Andre Engels) Date: Tue, 26 Aug 2008 15:05:41 +0200 Subject: [Tutor] Python installing in root In-Reply-To: <1219754693.15589.35.camel@lieryan-laptop> References: <mailman.55.1219744826.809.tutor@python.org> <1219754693.15589.35.camel@lieryan-laptop> Message-ID: <6faf39c90808260605r72df2f57xdba5e46598d47a80@mail.gmail.com> On Tue, Aug 26, 2008 at 2:44 PM, Lie Ryan <lie.1296 at gmail.com> wrote: > I have installed Python 2.5 on Windows Vista (Home Basic) on C:\Program > Files, so clearly this is not a global problem. My guess is that at the > work computer, you don't have write access to the directory you're > installing python to, so the installer defaults to the root C:\ (for > some odd reason, it's quite unusual to have access to root C:\ but not > <insert any other directory here>). Well, whatever it was, the problem has been solved now - a colleague found that I could get it where I wanted by executing the command as administrator, with the directory specified on command line. Thanks for thinking with me! -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Tue Aug 26 15:09:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Aug 2008 14:09:11 +0100 Subject: [Tutor] Why does the Hex builtin function in Python return a string? References: <978381.61844.qm@web59603.mail.ac4.yahoo.com> Message-ID: <g90v9q$me1$1@ger.gmane.org> "Py Hex" <pyhex at yahoo.com> wrote >>>> type(hex(12)) > <type 'str'> > > I get a string type back, i.e, '0xC' not 0xC Thats right because hex is a representation format. The data (12 in this case) is stored in binary on the PC. What you see as hex (or decimal or ocatal...) is just a string representation of the underlying binary data. > On the other hand, if I use 0x with data, Python > understands it is hex data and not a string value. > >>>> e = 0xCD >>>> type(e) > <type 'int'> Close. Python understands the string of characters you typed is in hex format and interprets the string as an integer value which it stores in binary internally. > How can I convert this string returned by hex builtin > function to data with 0x prefixed ? The 0x prefix is a string. The data is always in binary. You cannot convert a number to anything (other than int-float etc) you can only change its string representation. > Am I missing anything ? Yes, you are missing the underlying data representation within the machine. You need to distinguish clearly in your mind the difference between what is stored and what is displayed. The storage is always binary. The display is whatever format you ask for (with decimal as default) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Aug 26 15:13:55 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Aug 2008 14:13:55 +0100 Subject: [Tutor] Python installing in root References: <6faf39c90808260140v3bb8437h25cd73e3a4f117b2@mail.gmail.com> Message-ID: <g90vin$nl6$1@ger.gmane.org> "Andre Engels" <andreengels at gmail.com> wrote > Vista). On my private computer this works as it should, but on my > work > computer, it installs in the root directory of C: whatever directory > I > specify it to be installed into. Is this a known problem, and does > anybody know what to do about it? Python has no way of knowing whether the PC is at work or at home. There is nothing to prevent it installing where you tell it so far as the python installer goes. Therefore I assume something is set up differently on your work PC. Maybe a permissions thing? At an outside guess it's possible Python tries to install where you tell it and if it encounters an error it just uses the default location? But that sounds unlikely to me. Alan G From eric at ericabrahamsen.net Tue Aug 26 19:24:16 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Wed, 27 Aug 2008 01:24:16 +0800 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <1c2a2c590808260420k5c7c56d6y25450bad33dd0e2c@mail.gmail.com> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> <83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net> <1c2a2c590808260420k5c7c56d6y25450bad33dd0e2c@mail.gmail.com> Message-ID: <30E03AB2-6BA7-4982-8D8A-2320311546B7@ericabrahamsen.net> On Aug 26, 2008, at 7:20 PM, Kent Johnson wrote: > On Tue, Aug 26, 2008 at 1:36 AM, Eric Abrahamsen > <eric at ericabrahamsen.net> wrote: > >> So my test case: a Month has a 'child' attribute pointing at Week, >> which has >> a 'child' attribute pointing at Day, so they all know what kind of >> child >> instances iteration should produce. With nested loops, a Month >> produces one >> Week, that Week produces seven Days, then the next Week is >> produced, it >> makes seven more Days, etc. That much is easy. > > If all you want to do with the nested Month, etc is to iterate the > events in them, you could probably use a shared iterator. It would > have to be able to push-back items so that when you hit the > out-of-range item you could push it back on the iterator. Is a 'shared iterator' something special, or do you mean all the instances would draw their events from a single iterator? I'm not sure what this would look like. > > >> Then there's self.events. My original code looped over all of >> self.events >> for each child produced. A Month loops over its events four times, >> a Week >> seven times. This was the straightforward implementation, but it >> seemed >> inefficient. (I also, as you point out, might have been wrong about >> the way >> django QuerySets work). My thought was that only one loop over >> self.events >> should be necessary, in theory, since they're sorted by date. > > Instead of direct use of the list iterator, you could pass the list > and the starting index around. Then you don't have to keep finding > your place. That's a definite possibility, I'll try it out. Itertools.tee is also something I've yet to look at closely. Thanks for these hints. > > >> A for loop creates an iterator from a sequence and calls next() on >> it, and >> it creates an entirely new iterator each time you start a new for >> loop: > > I still don't understand your code but you may have another > misconception. Calling iter() on an iterator returns the same > iterator; it does not make a new iterator that holds the same place. > You can use itertools.tee() to split an iterator if that is what you > want to do. Just for the sake of argument, here's the principle I'm working from: ##### >>> lst = range(10) >>> iterlst = iter(lst) >>> iterlst.next() 0 >>> for x in iterlst: ... if x < 5: ... print x ... else: ... break ... 1 2 3 4 >>> for x in iterlst: ... print x ... 6 7 8 9 ##### So that's why I'm creating the iterator outside of the while loop in the original code, and then using a repeated for loop with a break to step through all the events only once. Of course, the fact that 5 isn't in there probably points to the source of my problems! The solution might be assigning iterlist.next() to a variable, and advancing the variable. Thanks, Eric From alan.gauld at btinternet.com Tue Aug 26 19:39:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Aug 2008 18:39:39 +0100 Subject: [Tutor] __iter__ loops, partitioning list among children References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net><1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com><1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net><1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com><F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net><57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net><1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com><83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net><1c2a2c590808260420k5c7c56d6y25450bad33dd0e2c@mail.gmail.com> <30E03AB2-6BA7-4982-8D8A-2320311546B7@ericabrahamsen.net> Message-ID: <g91f4v$lq3$1@ger.gmane.org> "Eric Abrahamsen" <eric at ericabrahamsen.net> wrote > So that's why I'm creating the iterator outside of the while loop in > the original code, and then using a repeated for loop with a break > to step through all the events only once. Of course, the fact that > 5 isn't in there probably points to the source of my problems! The > solution might be assigning iterlist.next() to a variable, and > advancing the variable. In that case wouldn't it be simpler to just use the index and manually control its value? Iterators are wonderful things but when I have to start bending things too far from vanilla I tend to go back to first principles. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Aug 26 20:22:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 26 Aug 2008 14:22:30 -0400 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <30E03AB2-6BA7-4982-8D8A-2320311546B7@ericabrahamsen.net> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> <83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net> <1c2a2c590808260420k5c7c56d6y25450bad33dd0e2c@mail.gmail.com> <30E03AB2-6BA7-4982-8D8A-2320311546B7@ericabrahamsen.net> Message-ID: <1c2a2c590808261122u1f4f66e5ra5fa274798c42348@mail.gmail.com> On Tue, Aug 26, 2008 at 1:24 PM, Eric Abrahamsen <eric at ericabrahamsen.net> wrote: > On Aug 26, 2008, at 7:20 PM, Kent Johnson wrote: >> If all you want to do with the nested Month, etc is to iterate the >> events in them, you could probably use a shared iterator. It would >> have to be able to push-back items so that when you hit the >> out-of-range item you could push it back on the iterator. > > Is a 'shared iterator' something special, or do you mean all the instances > would draw their events from a single iterator? I'm not sure what this would > look like. It's nothing special, I just mean that all instances would share an iterator. You would pass the iterator to the iteration function. > Just for the sake of argument, here's the principle I'm working from: > > ##### >>>> lst = range(10) >>>> iterlst = iter(lst) >>>> iterlst.next() > 0 >>>> for x in iterlst: > ... if x < 5: > ... print x > ... else: > ... break > ... > 1 > 2 > 3 > 4 >>>> for x in iterlst: > ... print x > ... > 6 > 7 > 8 > 9 > ##### > > So that's why I'm creating the iterator outside of the while loop in the > original code, and then using a repeated for loop with a break to step > through all the events only once. Of course, the fact that 5 isn't in there > probably points to the source of my problems! The solution might be > assigning iterlist.next() to a variable, and advancing the variable. The problem is that the first loop consumes the 5 from the iterator but doesn't actually process it. That is why you need an iterator with push-back - so you can put the 5 "back in" the iterator and get it out again in the next loop. http://code.activestate.com/recipes/502304/ Though working with indices directly might be simpler. Kent From jeffpeery at seametrics.com Tue Aug 26 20:31:44 2008 From: jeffpeery at seametrics.com (Jeff Peery) Date: Tue, 26 Aug 2008 11:31:44 -0700 Subject: [Tutor] executing a script from a script Message-ID: <D1B34694B371442DAF1657140BEA5521@seametrics.local> Hello, I have a simple wx app that I need some help with. This application uses the serial ports to communicate with an industrial product. I first check that my python application is compatible with the industrial product by asking the industrial product for its revision number. If the revision number is too old I want to kill my python application and launch an older python application. To do this I am using the following: # launch old program execfile('theoldpythonprogram.py') # kill this App (wx.Frame object) self.Destroy() The problem is that the self.Destroy() seems to kill both the current python program and the one I just launched. How can I launch a new program and kill the current one without killing the new one as well? Thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080826/d533a6b1/attachment.htm> From ruivaldo at gmail.com Tue Aug 26 23:15:04 2008 From: ruivaldo at gmail.com (rui) Date: Tue, 26 Aug 2008 18:15:04 -0300 Subject: [Tutor] executing a script from a script In-Reply-To: <D1B34694B371442DAF1657140BEA5521@seametrics.local> References: <D1B34694B371442DAF1657140BEA5521@seametrics.local> Message-ID: <d4a50f170808261415l449ecdectd9d540c1941c7c02@mail.gmail.com> On Tue, Aug 26, 2008 at 3:31 PM, Jeff Peery <jeffpeery at seametrics.com> wrote: > Hello, > > I have a simple wx app that I need some help with. This application uses the > serial ports to communicate with an industrial product. I first check that > my python application is compatible with the industrial product by asking > the industrial product for its revision number. If the revision number is > too old I want to kill my python application and launch an older python > application. To do this I am using the following: > > > > # launch old program > > execfile('theoldpythonprogram.py') > > # kill this App (wx.Frame object) > > self.Destroy() > > > > The problem is that the self.Destroy() seems to kill both the current python > program and the one I just launched. How can I launch a new program and kill > the current one without killing the new one as well? > > Hi Jeff, The problem is that execfile runs the script inside the current python interpreter. To run this as -- really -- an external process, look at: http://blog.doughellmann.com/2007/07/pymotw-subprocess.html Cheers and good luck. Just a tip, using inheritance could solve your problem more elegantly. [ As quatro melhores coisas do mundo s?o tr?s: forr? e mulher. ] > > Thanks! > > > > Jeff > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cspears2002 at yahoo.com Wed Aug 27 08:03:49 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 26 Aug 2008 23:03:49 -0700 (PDT) Subject: [Tutor] renumbering a sequence Message-ID: <411313.99505.qm@web51605.mail.re2.yahoo.com> I'm trying to write a script that will renumber items in a list. Here is the list: unordered_list = ["frame.0029.dpx", "frame.0028.dpx", "frame.0025.dpx", "frame.0026.dpx", "frame.0027.dpx", "frame.0017.dpx", "frame.0019.dpx", "frame.0023.dpx", "frame.0018.dpx", "frame.0019.dpx", "frame.0020.dpx", "frame.0021.dpx", "frame.0022.dpx", "frame.0023.dpx", "frame.0024.dpx", "frame.0000.dpx"] Basically, I need the script to first sort the list and then renumber the sequence, so the list will be as follows: frame.0000.dpx -> originally frame.0000.dpx frame.0001.dpx -> originally frame.0017.dpx frame.0002.dpx -> originally frame.0018.dpx frame.0003.dpx -> originally frame.0019.dpx etc. If the first frame is one, then nothing needs to be done to the sequence. If the first frame is zero and the next frame is not one, then the sequence needs to be renumbered by converting the frames after zero. If the first frame is not one, then the list needs to be renumbered to begin at one. Here is what I have written so far: #!/usr/bin/python def renumber_frame(orig_frame): #break up frame name using period frame_string_list = orig_frame.split(".") #renumber frame <-not sure how to do this new_frame = frame_string_list[0] + "." + frame_number + "." frame_string_list[2] return new_frame unordered_list = ["frame.0029.dpx", "frame.0028.dpx", "frame.0025.dpx", "frame.0026.dpx", "frame.0027.dpx", "frame.0017.dpx", "frame.0019.dpx", "frame.0023.dpx", "frame.0018.dpx", "frame.0019.dpx", "frame.0020.dpx", "frame.0021.dpx", "frame.0022.dpx", "frame.0023.dpx", "frame.0024.dpx", "frame.0000.dpx"] ordered_list = sorted(unordered_list) test_frame_1 = ordered_list[0].split('.')[1] test_frame_2 = ordered_list[1].split('.')[1] if test_frame_1 == "0000": if test_frame_2 =! "0001": print "Sequence needs to be renumbered" for frame in ordered_list: new_frame = renumber_frame(frame) print new_frame elif test_frame_1 != "0001" print "Sequence needs to be renumbered" for frame in ordered_list: new_frame = renumber_frame(frame) print new_frame else: print "Sequence is fine" As you can see, the only part I haven't figured out is the actual renumbering. Can't figure out how to do the following: 0017 convert to -> 0001 0018 convert to -> 0002 0019 convert to -> 0003 etc. Any hints? Thanks. From simozack at yahoo.it Wed Aug 27 08:46:37 2008 From: simozack at yahoo.it (simone) Date: Wed, 27 Aug 2008 08:46:37 +0200 Subject: [Tutor] renumbering a sequence In-Reply-To: <411313.99505.qm@web51605.mail.re2.yahoo.com> References: <411313.99505.qm@web51605.mail.re2.yahoo.com> Message-ID: <48B4F84D.5060905@yahoo.it> Christopher Spears ha scritto: > As you can see, the only part I haven't figured out is the actual renumbering. Can't figure out how to do the following: > 0017 convert to -> 0001 > 0018 convert to -> 0002 > 0019 convert to -> 0003 > etc. > > Any hints? Thanks. IMHO, you can renumber everything without testing the right order. An example: for progress, file_name in enumerate(ordered_list): frame, num, ext = file_name.split('.') print "%s.%s.%s" % (frame, str(progress).zfill(4), ext) And you will have what you want (if I understand right...). -- Simone Chiacchiera con i tuoi amici in tempo reale! http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com From alan.gauld at btinternet.com Wed Aug 27 09:53:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Aug 2008 08:53:01 +0100 Subject: [Tutor] renumbering a sequence References: <411313.99505.qm@web51605.mail.re2.yahoo.com> Message-ID: <g93151$896$1@ger.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote > ordered_list = sorted(unordered_list) > > test_frame_1 = ordered_list[0].split('.')[1] > test_frame_2 = ordered_list[1].split('.')[1] > > if test_frame_1 == "0000": > if test_frame_2 =! "0001": > print "Sequence needs to be renumbered" > for frame in ordered_list: > new_frame = renumber_frame(frame) > print new_frame > elif test_frame_1 != "0001" > print "Sequence needs to be renumbered" > for frame in ordered_list: > new_frame = renumber_frame(frame) > print new_frame > else: > print "Sequence is fine" You can change the test sequence to avoid the code duplication if tf1 == '0000' and tf2 == '0001': print 'sequence fine' else print 'renumber sequence' for frame in ....etc > As you can see, the only part I haven't figured out is the > actual renumbering. Can't figure out how to do the following: > 0017 convert to -> 0001 Instead of splitting and reconstructing you could use a regex to locate the number section and usere.sub() to replace the old number with the new sequence number Not sure if that would be any faster but it might be more concise. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ptmcg at austin.rr.com Wed Aug 27 15:24:39 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 27 Aug 2008 08:24:39 -0500 Subject: [Tutor] renumbering a sequence In-Reply-To: <mailman.47.1219831224.7311.tutor@python.org> References: <mailman.47.1219831224.7311.tutor@python.org> Message-ID: <C29295A69523458B9AAB7D850898F85C@AWA2> I am thinking along similar lines as Simone, but I suspect there is still a missing step. I think you need to know what the mapping is from old name to new name, so that you can do something like rename or copy the files that these names represent. Python's built-in zip() method does the trick here (zip comes in handy in so many ways, it is a good tool to add to your at-hand Python skill set). Don't think of "zip" as in the common file compression scheme. In Python, zip() acts like a zipper, matching together the entries from 2 or more lists the way a zipper matches the teeth from its two sides. For instance, here is a simple example of zip() from the command line: >>> print zip("ABC","123") [('A', '1'), ('B', '2'), ('C', '3')] You can imagine how easy it would be to make a dict with zip: >>> print dict(zip("ABC","123")) {'A': '1', 'C': '3', 'B': '2'} For your problem, here is how to zip your old and new file lists together, and a hypothetical use of such a mapping (to rename the original files): import os original_list = sorted(unordered_list) # use a list comprehension to construct list of new file names in order new_list = [ "frame.%04d.dpx" % i for i in xrange(len(original_list)) ] # map old names to new names - zip creates a list of tuples # using an item from each list in order file_mapping = zip(original_list, new_list) # rename files to consecutive order for oldname,newname in file_mapping: if oldname != newname: os.rename(oldname,newname) -- Paul From ptmcg at austin.rr.com Wed Aug 27 15:36:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 27 Aug 2008 08:36:53 -0500 Subject: [Tutor] renumbering a sequence In-Reply-To: <mailman.47.1219831224.7311.tutor@python.org> References: <mailman.47.1219831224.7311.tutor@python.org> Message-ID: <5E7A607698454D6FB31D26A866CF6470@AWA2> One problem with my previous post. I didn't look closely enough at the original list of files, it turns out you have multiple entries for some of them. If you used the glob module to create this list (with something like "original_list = glob.glob('frame.*.dpx')"), then there should be no problem with duplicates. But if the list was hand generated, you should probably check for duplicates first. The easiest way to do this is to use a Python set: if len(set(original_names)) < len(original_names): print "Watch out! There are duplicate file names in the list!" Of course, having duplicates in the original list makes no matter in the generation of a new list of consecutively-numbered file names. The problems will arise when you go to actually do something with the generated list, such as the renaming example I posted earlier. -- Paul From sierra_mtnview at sbcglobal.net Wed Aug 27 17:36:59 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 27 Aug 2008 08:36:59 -0700 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program Message-ID: <48B5749B.6010400@sbcglobal.net> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080827/4d591694/attachment.htm> From spython01 at gmail.com Wed Aug 27 18:22:46 2008 From: spython01 at gmail.com (Samir Parikh) Date: Wed, 27 Aug 2008 12:22:46 -0400 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <48B5749B.6010400@sbcglobal.net> References: <48B5749B.6010400@sbcglobal.net> Message-ID: <50a597410808270922v69ad415cg41c95f8f7282053e@mail.gmail.com> On Wed, Aug 27, 2008 at 11:36 AM, Wayne Watson <sierra_mtnview at sbcglobal.net> wrote: > I use IDLE on XP, and would like to know if there's an easier way to start > it than what I use? I pick on a py file, and then use the pull down menu, > right-click, to select IDLE. That means I start off with some program I may > want to erase to get started on a new program. It's easy to clear the text > with a Ctrl-C and then delete. However, that leaves the file as abc.py, > where abc.py is the original program. Now I need to be careful with my Save. > I'd like to start IDLE on new programs in such a way that when I perform a > Save the program goes into a folder of my py files, and not somewhere else. > -- Hi Wayne, Do you not see IDLE under Programs when you click the <Start> button? (I'm currently on my Linux machine so I don't recall the exact path, but that's how I access it when I'm on my laptop running XP.). Once you launch IDLE, then you can click File > New File and save your new Python program to any directory. Thanks. Samir From cappy2112 at gmail.com Wed Aug 27 19:00:30 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 27 Aug 2008 10:00:30 -0700 Subject: [Tutor] using sys.excepthook to handled unhandled exceptions Message-ID: <8249c4ac0808271000k520b958l90bf04aae51e20b@mail.gmail.com> The original authors left asserts in many places and I don't want the people using the code to see the ugly tracebacks. want to add an unhandled exception handler to a large framework that I'm maintaining, to make the applications behave better, Users of a program shouldn't need to know anything about the language in order to have an idea of what caused the error. With that in mind, I thought I would add a handler which logs the tracebacks to a file, display a 1-line message about the error on the screen, so the user has some idea of what happened, along with a simple message like this "An unhandled exception has occured. This program will terminate. Please email the "ErrorReport.txt" file to the developers" I would like to hear from "people who have already assigned their own function to sys.excepthook" as to how they approached this problem, and what issues they encountered, if any. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080827/780d3dda/attachment.htm> From cappy2112 at gmail.com Wed Aug 27 21:18:15 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 27 Aug 2008 12:18:15 -0700 Subject: [Tutor] using sys.excepthook to handle unhandled exception (corrected and reposted) Message-ID: <8249c4ac0808271218n56e8dacbx897191830c6a9171@mail.gmail.com> I'm maintaining a large framework of python code where the original authors left many assert statements. When an unhandled exception occurs, the traceback is displayed on the screen. Ideally, I don't want the users to see the tracebacks from unhandled exceptions, but rather a short, useful message. Users of a program shouldn't need to know anything about the language the program was written in order to have an idea of what caused the error. I want to add an "unhandled exception handler" which logs the tracebacks to a file, display a 1 line message as to where or why the exception occurred. Assigning my exception logger function to sys.excepthook is what I have in mind. This exception logger will also display a message like this. "An unhandled exception has occurred. This program will terminate. Please email the "ErrorReport.txt" file to the developers" Adding a function to log the tracebacks is easy, I'm more interested in the side affects caused by assigning a function to sys.excepthook. The framework I'm maintaining does NOT already use sys.excepthook. That is a good beginning. ;-) I would like to hear from the experiences of people "who have assigned an exception handler function to sys.excepthook" as to how they approached this problem. More specifically, what issues they encountered, if any. Thanks From kent37 at tds.net Wed Aug 27 22:09:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 27 Aug 2008 16:09:53 -0400 Subject: [Tutor] using sys.excepthook to handle unhandled exception (corrected and reposted) In-Reply-To: <8249c4ac0808271218n56e8dacbx897191830c6a9171@mail.gmail.com> References: <8249c4ac0808271218n56e8dacbx897191830c6a9171@mail.gmail.com> Message-ID: <1c2a2c590808271309g3ded236al151c938aca2fa6e8@mail.gmail.com> On Wed, Aug 27, 2008 at 3:18 PM, Tony Cappellini <cappy2112 at gmail.com> wrote: > I would like to hear from the experiences of people "who have assigned > an exception handler function to sys.excepthook" as to how they > approached > this problem. More specifically, what issues they encountered, if any. Have you searched comp.lang.python? There seems to be quite a bit of discussion there. Kent From alan.gauld at btinternet.com Thu Aug 28 01:48:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2008 00:48:45 +0100 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program References: <48B5749B.6010400@sbcglobal.net> Message-ID: <g94p52$off$1@ger.gmane.org> "Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote > would like to know if there's an easier way to start it than > what I use? I pick on a py file, and then use the pull down menu, > right-click, to select IDLE. Yes, it should be on the Start menu possibly listed as Python GUI. Or you can set up a shortcut to it by selecting idle.pyw in explorer and creating a shortcut and dragging it to your desktop. Or you could do yourself a favour and get the Pythonwin extensions and use Pythonwin instead. IDLE is fine for a cross platform IDE but it is ugly and less feature rich than Pythonwin. And the pythonwin installer sets up the menus etc for you. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 28 01:51:35 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2008 00:51:35 +0100 Subject: [Tutor] using sys.excepthook to handled unhandled exceptions References: <8249c4ac0808271000k520b958l90bf04aae51e20b@mail.gmail.com> Message-ID: <g94pac$otd$1@ger.gmane.org> "Tony Cappellini" <cappy2112 at gmail.com> wrote > With that in mind, I thought I would add a handler which logs the > tracebacks > to a file, display a 1-line message about the error on the screen, > so the > user has some > idea of what happened, along with a simple message like this I tend to do that after I get everything working by just wrapping main() in a try/except clause that catches everything then mapping any errors to friendly strings and logging the traceback if logging is enabled. In other words I don't mess with the excepthook value. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From winglion1 at 163.com Thu Aug 28 03:59:05 2008 From: winglion1 at 163.com (Yang) Date: Thu, 28 Aug 2008 09:59:05 +0800 Subject: [Tutor] print the hole unicode list Message-ID: <48B6119B.14D89C.08581@m5-82.163.com> Hello, I am trying to print out the hole unicode char list in window! form 0-65535. I use the winxp in simple chinese LOCAL! the ascii form 0-127 and CJK chars form 0X4E00-0X9FA4 can be print out! Other ucode chars case this error "UnicodeEncodeError: 'gbk' codec can't encode character u'\u9fa6' in position 0" my code is here: for i in range(0,65536 ): uchar=unicode("\u%04X"%i,"unicode-escape") print "%x :"%i,uchar how can I achive a hole unicode list? Or can it be done? ????????????????Yang ????????????????winglion1 at 163.com ????????????????????2008-08-28 From agilfoy at frontiernet.net Thu Aug 28 08:33:19 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Thu, 28 Aug 2008 06:33:19 +0000 Subject: [Tutor] Having trouble with a component of the random module Message-ID: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> One of my for-fun Python products is a booster-pack generator for trading card games (specifically, Magic the Gathering, the one game of the genre that I play heavily) Somewhat like baseball cards, the cards in a pack are a somewhat-random selection of cards from the set in question, broken down by rarity levels. There are anywhere from two to six rarity levels/groupings per set; this depends on the set in question. I have a function for 2-list sets, another for 3, another for 4, another for 5, and another for 6. By lists I mean the following: If a set has, say, 2 rarity levels in it, I make 2 lists, one per rarity level. Each list is a text file that has the names of each card of that rarity level in that set, one per line. (There are no blank lines.) My function is set up kind of like this: Import the lists - via open("filename.txt").readlines() This action creates a List, with strings as the list elements, one string/element for each line of the imported text file I use random.sample to make the selection, random.sample(population, k) " for card in random.sample(Common, C): print card " Common is the 1st list, with the names of the commons in the set as the items in that list. The C variable is an integer, the amount of commons in a booster pack of that set. Say, if there are 11 commons in a booster pack of that set, I feed 11 as the value for C, and the code snippet above proceeds to print 11 randomly-selected names from the Commons list My program does the same thing for the second list (Uncommon), the third list (Rare), the fourth list (BasicLand), the fifth list (SpecialA), and the sixth list (SpecialB). For card sets that use two, three, or four lists, the results are displayed just fine. For card sets that use five or six lists, the results for the first four are displayed just fine, and then I get this: The code that processes the 1st, 2nd, 3rd and 4th lists is very similar to the code that processes the 5th and 6th, so I don't see what's happening. Traceback (most recent call last): File "C:\Documents and Settings\Alan\My Documents\_Alan_Programming\trunk\BoosterPackMaker\BoosterPackMaker.py", line 104, in <module> SixList_PackChooser(C_list, UC_list, R_list, BL_list, SpecialA_list, SpecialB_list, C, UC, R, BL, SA, SB) File "C:\Documents and Settings\Alan\My Documents\_Alan_Programming\trunk\BoosterPackMaker\PackGenerator.py", line 367, in SixList_PackChooser for card in random.sample(SpecialA, SA): File "C:\Python25\lib\random.py", line 303, in sample raise ValueError, "sample larger than population" ValueError: sample larger than population Looking at the mentioned line in random.py, I don't see how my program is triggering the ValueError. The number of items I want from a list is smaller than the population (number of items) in the list, so it should work. In this specific case, I'm asking for one item from a five-item list. Overall, more code is involved that I think can be represented in a few cut'n'paste snippets; how would I go about providing the files in question for interested parties to look at? (There's the Python file for my front-end UI code, the Python module file for my processing function, and the relevant text files) Apologizing for message length; I'm just trying to clearly explain the problem that I want assistance on. From eric at ericabrahamsen.net Thu Aug 28 08:59:19 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Thu, 28 Aug 2008 14:59:19 +0800 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <1c2a2c590808261122u1f4f66e5ra5fa274798c42348@mail.gmail.com> References: <D253503B-EA09-4703-A604-658EA4223388@ericabrahamsen.net> <1c2a2c590808230822u7ce6fd05u12c55f99c2dffdae@mail.gmail.com> <1747E409-2795-4293-BA1C-D762081498D6@ericabrahamsen.net> <1c2a2c590808240420n54f4a66l32ca8b816420e17b@mail.gmail.com> <F96EE604-42BE-408C-B445-52B973421449@ericabrahamsen.net> <57DC8F55-8294-46DF-B77A-A5F8FE6A6B85@ericabrahamsen.net> <1c2a2c590808251012t580189c1m592e1f1dfdc74ec5@mail.gmail.com> <83E5003A-077A-4EC3-88AE-093EBCE0FEEE@ericabrahamsen.net> <1c2a2c590808260420k5c7c56d6y25450bad33dd0e2c@mail.gmail.com> <30E03AB2-6BA7-4982-8D8A-2320311546B7@ericabrahamsen.net> <1c2a2c590808261122u1f4f66e5ra5fa274798c42348@mail.gmail.com> Message-ID: <1DF5151E-73DD-4AC7-A36D-D5A32F20AB74@ericabrahamsen.net> I finally got my iterator-based version working, only to discover that it's nearly four times slower than the brute-force multiple-loops version I started with! Then I tried just adding an incrementing index to the loop, so that each loop only ran through self.events[last_index:], but that was still twice as slow as without the index. I suppose it's the overhead of incrementing the variable, or maybe some optimization in Python's internals, but the take home lesson was definitely 'leave well enough alone'. Anyway, thanks again for the advice, it's been a learning experience... E On Aug 27, 2008, at 2:22 AM, Kent Johnson wrote: > On Tue, Aug 26, 2008 at 1:24 PM, Eric Abrahamsen > <eric at ericabrahamsen.net> wrote: >> On Aug 26, 2008, at 7:20 PM, Kent Johnson wrote: > >>> If all you want to do with the nested Month, etc is to iterate the >>> events in them, you could probably use a shared iterator. It would >>> have to be able to push-back items so that when you hit the >>> out-of-range item you could push it back on the iterator. >> >> Is a 'shared iterator' something special, or do you mean all the >> instances >> would draw their events from a single iterator? I'm not sure what >> this would >> look like. > > It's nothing special, I just mean that all instances would share an > iterator. You would pass the iterator to the iteration function. > >> Just for the sake of argument, here's the principle I'm working from: >> >> ##### >>>>> lst = range(10) >>>>> iterlst = iter(lst) >>>>> iterlst.next() >> 0 >>>>> for x in iterlst: >> ... if x < 5: >> ... print x >> ... else: >> ... break >> ... >> 1 >> 2 >> 3 >> 4 >>>>> for x in iterlst: >> ... print x >> ... >> 6 >> 7 >> 8 >> 9 >> ##### >> >> So that's why I'm creating the iterator outside of the while loop >> in the >> original code, and then using a repeated for loop with a break to >> step >> through all the events only once. Of course, the fact that 5 isn't >> in there >> probably points to the source of my problems! The solution might be >> assigning iterlist.next() to a variable, and advancing the variable. > > The problem is that the first loop consumes the 5 from the iterator > but doesn't actually process it. That is why you need an iterator with > push-back - so you can put the 5 "back in" the iterator and get it out > again in the next loop. > http://code.activestate.com/recipes/502304/ > Though working with indices directly might be simpler. > > Kent From srilyk at gmail.com Thu Aug 28 11:44:49 2008 From: srilyk at gmail.com (W W) Date: Thu, 28 Aug 2008 04:44:49 -0500 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> Message-ID: <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> On Thu, Aug 28, 2008 at 1:33 AM, Alan Gilfoy <agilfoy at frontiernet.net>wrote: > > The number of items I want from a list is smaller than the population > (number of items) in the list, so it should work. > > In this specific case, I'm asking for one item from a five-item list. Are you sure? change this: for card in random.sample(SpecialA, SA): to this: print "Special: ", SpecialA, "\nSA: ", SA for card in random.sample(SpecialA, SA): then give us the output. I'll bet that your SA value is never reset to 1. > Overall, more code is involved that I think can be represented in a few > cut'n'paste snippets; how would I go about providing the files in question > for interested parties to look at? http://paste.pocoo.org I believe. > > (There's the Python file for my front-end UI code, the Python module file > for my processing function, and the relevant text files) > > Apologizing for message length; I'm just trying to clearly explain the > problem that I want assistance on. You've obviously researched enough to know this: >>> mylist = [1, 2, 3, 4, 5] >>> from random import sample >>> sample(mylist, 3) [2, 1, 4] >>> sample(mylist, 10) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/random.py", line 303, in sample raise ValueError, "sample larger than population" ValueError: sample larger than population So give the print statement before your for loop a try and see what you come up with. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080828/591864dd/attachment.htm> From srilyk at gmail.com Thu Aug 28 11:53:37 2008 From: srilyk at gmail.com (W W) Date: Thu, 28 Aug 2008 04:53:37 -0500 Subject: [Tutor] print the hole unicode list In-Reply-To: <48B6119B.14D89C.08581@m5-82.163.com> References: <48B6119B.14D89C.08581@m5-82.163.com> Message-ID: <333efb450808280253s3a065d5bj19050d0bca25af0c@mail.gmail.com> Well, on my linux box (ubuntu) it had no problem with this: for i in range(0, 65536): uchar=unicode("\u%04X"%i,"unicode-escape") print uchar So my guess is you're missing some character in your set, but I'm not sure. HTH -Wayne On Wed, Aug 27, 2008 at 8:59 PM, Yang <winglion1 at 163.com> wrote: > Hello, > I am trying to print out the hole unicode char list in window! form > 0-65535. > I use the winxp in simple chinese LOCAL! the ascii form 0-127 and CJK chars > form > 0X4E00-0X9FA4 can be print out! Other ucode chars case this error > "UnicodeEncodeError: 'gbk' codec can't encode character u'\u9fa6' in > position 0" > > my code is here: > for i in range(0,65536 ): > uchar=unicode("\u%04X"%i,"unicode-escape") > print "%x :"%i,uchar > > how can I achive a hole unicode list? Or can it be done? > > ????????????????Yang > ????????????????winglion1 at 163.com > ????????????????????2008-08-28 > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080828/79e0146f/attachment.htm> From kent37 at tds.net Thu Aug 28 12:35:49 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Aug 2008 06:35:49 -0400 Subject: [Tutor] print the hole unicode list In-Reply-To: <48B6119B.14D89C.08581@m5-82.163.com> References: <48B6119B.14D89C.08581@m5-82.163.com> Message-ID: <1c2a2c590808280335l754210d0x3468161516ef63a@mail.gmail.com> On Wed, Aug 27, 2008 at 9:59 PM, Yang <winglion1 at 163.com> wrote: > Hello, > I am trying to print out the hole unicode char list in window! form 0-65535. > I use the winxp in simple chinese LOCAL! the ascii form 0-127 and CJK chars form > 0X4E00-0X9FA4 can be print out! Other ucode chars case this error > "UnicodeEncodeError: 'gbk' codec can't encode character u'\u9fa6' in position 0" > > my code is here: > for i in range(0,65536 ): > uchar=unicode("\u%04X"%i,"unicode-escape") A simpler way to do this is uchar = unichr(i) > print "%x :"%i,uchar > > how can I achive a hole unicode list? Or can it be done? I guess the error comes from the print statement. (Please include the traceback with error reports.) If so, the problem is that your console can't represent all the characters that you want to print. It looks like your console encoding is 'gbk' and not every unicode character can be represented in this encoding. One way to fix this is to explicitly convert to gbk and tell Python to substitute a ? character for the character that can't be converted. To do this, use the str.encode() method and pass a second argument of 'replace'. Then the whole program becomes for i in range(0, 65536): c = unichr(i).encode('gbk', 'replace') print c Another solution might be to change your console to UTF-8 encoding, if that is possible on your computer. If your goal is to see the characters, the resources at Unicode.org might be more help, for example: http://www.unicode.org/charts/ Kent From michael at arpsorensen.dk Thu Aug 28 13:56:07 2008 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Thu, 28 Aug 2008 13:56:07 +0200 Subject: [Tutor] Calling an external program/daemon that doesn't exit/return In-Reply-To: <1618520808280406g4a5f34c5x5ea985a8b64c5991@mail.gmail.com> References: <1618520808280406g4a5f34c5x5ea985a8b64c5991@mail.gmail.com> Message-ID: <1618520808280456r714e8c1exf86217cbcf1fcd56@mail.gmail.com> Hi again. Aparantly it was as simple as: os.system("nohup /code/daemon.py &") I know it's more correct to write a real deamon startet from a runlevel, but that will have to wait until later. :-) Med venlig hilsen/Kind regards Michael B. Arp S?rensen Programm?r / BOFH "Ride out and meet them." On Thu, Aug 28, 2008 at 1:06 PM, Michael Bernhard Arp S?rensen < michael at arpsorensen.dk> wrote: > Hi there. > > I'm trying to find some info about starting a program from python. I just > want to start it and move on. The program will not end until reboot. > > Any clues? > > Med venlig hilsen/Kind regards > > Michael B. Arp S?rensen > Programm?r / BOFH > > "Ride out and meet them." > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080828/b2201765/attachment.htm> From lie.1296 at gmail.com Tue Aug 26 22:05:45 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 27 Aug 2008 03:05:45 +0700 Subject: [Tutor] __iter__ loops, partitioning list among children In-Reply-To: <mailman.22999.1219774962.920.tutor@python.org> References: <mailman.22999.1219774962.920.tutor@python.org> Message-ID: <1219781145.7219.5.camel@lieryan-laptop> > > > Just for the sake of argument, here's the principle I'm working > from: > > > > ##### > >>>> lst = range(10) > >>>> iterlst = iter(lst) > >>>> iterlst.next() > > 0 > >>>> for x in iterlst: > > ... if x < 5: > > ... print x > > ... else: > > ... break > > ... > > 1 > > 2 > > 3 > > 4 > >>>> for x in iterlst: > > ... print x > > ... > > 6 > > 7 > > 8 > > 9 > > ##### If that contrived case is the case, you could change the code a bit to make 5 appears: for x in iterlst: print x if x >= 5: break for x in iterlst: print x > > > > So that's why I'm creating the iterator outside of the while loop in > the > > original code, and then using a repeated for loop with a break to > step > > through all the events only once. Of course, the fact that 5 isn't > in there > > probably points to the source of my problems! The solution might be > > assigning iterlist.next() to a variable, and advancing the variable. > > The problem is that the first loop consumes the 5 from the iterator > but doesn't actually process it. That is why you need an iterator with > push-back - so you can put the 5 "back in" the iterator and get it out > again in the next loop. > http://code.activestate.com/recipes/502304/ > Though working with indices directly might be simpler. From lie.1296 at gmail.com Thu Aug 28 14:23:02 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 28 Aug 2008 19:23:02 +0700 Subject: [Tutor] how do I create a lists of values associated with a key? Message-ID: <d03e25950808280523s691d0f65i78ea4082553fe361@mail.gmail.com> Message: 8 Date: Thu, 31 Jul 2008 20:16:54 -0700 (PDT) From: Angela Yang <angelayian at yahoo.com> Subject: [Tutor] how do I create a lists of values associated with a key? To: tutor at python.org Message-ID: <279879.31091.qm at web50107.mail.re2.yahoo.com> Content-Type: text/plain; charset="iso-8859-1" > That did not work because list index is not numeric. Dictionary is an unordered set (list is an ordered set) indexed by a immutable value (e.g. string, numbers, tuple) > But for dictionaries, it is key - value pairs.? But I need key -> multiple values. That would mean, a dictionary of lists. Dictionary keys cannot be a mutable (i.e. list cannot be a dictionary key) but dictionary's value may be mutable. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080828/8afa6af7/attachment.htm> From michael at arpsorensen.dk Thu Aug 28 13:06:47 2008 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Thu, 28 Aug 2008 13:06:47 +0200 Subject: [Tutor] Calling an external program/daemon that doesn't exit/return Message-ID: <1618520808280406g4a5f34c5x5ea985a8b64c5991@mail.gmail.com> Hi there. I'm trying to find some info about starting a program from python. I just want to start it and move on. The program will not end until reboot. Any clues? Med venlig hilsen/Kind regards Michael B. Arp S?rensen Programm?r / BOFH "Ride out and meet them." -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080828/89aa76eb/attachment.htm> From metolone+gmane at gmail.com Thu Aug 28 15:52:22 2008 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 28 Aug 2008 06:52:22 -0700 Subject: [Tutor] print the hole unicode list References: <48B6119B.14D89C.08581@m5-82.163.com> Message-ID: <g96aih$jjs$1@ger.gmane.org> "Yang" <winglion1 at 163.com> wrote in message news:48B6119B.14D89C.08581 at m5-82.163.com... > Hello, > I am trying to print out the hole unicode char list in window! form > 0-65535. > I use the winxp in simple chinese LOCAL! the ascii form 0-127 and CJK > chars form > 0X4E00-0X9FA4 can be print out! Other ucode chars case this error > "UnicodeEncodeError: 'gbk' codec can't encode character u'\u9fa6' in > position 0" > > my code is here: > for i in range(0,65536 ): > uchar=unicode("\u%04X"%i,"unicode-escape") > print "%x :"%i,uchar > > how can I achive a hole unicode list? Or can it be done? Your console encoding is 'gbk', which can't display all the Unicode characters. The following code can be used to generate all the characters into a file using an encoding that supports all Unicode characters, and then that file can be viewed in a program that supports the encoding (like Notepad for this example). Still, what characters you see will depend on the font used. Fonts generally do not support display of every Unicode character. import codecs f=codecs.open('unicode.txt','wt',encoding='utf-8') for i in xrange(32,0x10000): # skip control chars if i < 0xD800 or i > 0xDFFF: # skip surrogate pair chars f.write(u'%04X: %s\t' % (i,unichr(i))) f.close() -Mark From agilfoy at frontiernet.net Thu Aug 28 17:29:17 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Thu, 28 Aug 2008 15:29:17 +0000 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> Message-ID: <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> Quoting W W <srilyk at gmail.com>: >> The number of items I want from a list is smaller than the population >> (number of items) in the list, so it should work. >> >> In this specific case, I'm asking for one item from a five-item list. > > Are you sure? > > change this: > for card in random.sample(SpecialA, SA): > > to this: > > print "Special: ", SpecialA, "\nSA: ", SA > for card in random.sample(SpecialA, SA): > > then give us the output. I'll bet that your SA value is never reset to 1. > There is a part of my front-end code that declares the SA variable as equal to 1 for the card set in question, and feeds that into the processing function. Changing the block of code, as you suggest, still gets me a traceback: Special: [] SA: 1 Traceback (most recent call last): File "C:\Documents and Settings\Alan\My Documents\_Alan_Programming\trunk\BoosterPackMaker\BoosterPackMaker.py", line 104, in <module> SixList_PackChooser(C_list, UC_list, R_list, BL_list, SpecialA_list, SpecialB_list, C, UC, R, BL, SA, SB) File "C:\Documents and Settings\Alan\My Documents\_Alan_Programming\trunk\BoosterPackMaker\PackGenerator.py", line 367, in SixList_PackChooser for card in random.sample(SpecialA, SA): File "C:\Python25\lib\random.py", line 303, in sample raise ValueError, "sample larger than population" ValueError: sample larger than population So, I'm asking my program to pick 1 item from a 0-item list. How there are zero items in the list, I don't know. That must be the problem. > > You've obviously researched enough to know this: >>>> mylist = [1, 2, 3, 4, 5] >>>> from random import sample >>>> sample(mylist, 3) > [2, 1, 4] >>>> sample(mylist, 10) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/usr/lib/python2.5/random.py", line 303, in sample > raise ValueError, "sample larger than population" > ValueError: sample larger than population > Okay, asking for 3 items from a 5-item list works, and asking for 10 items from a 5-item list doesn't work. It should be trying to pick 1 item from the 5-item SpecialA list, but somehow the SpecialA list has zero items in it. > > So give the print statement before your for loop a try and see what you come > up with. Okay, I cut'n'pasted it before the traceback message. > > HTH, > Wayne Thank you. ----------------------------------------------- SixList_PackChooser(C_list, UC_list, R_list, BL_list, SpecialA_list, SpecialB_list, C, UC, R, BL, SA, SB) ^ The error occurs in this function. The program picks C number of items from C_list and displays them just fine. The program picks UC number of items from UC_list and displays them just fine. The program picks R number of items from R_list and displays them just fine. The program picks BL number of items from BL_list and displays them just fine. Looking at my user-interface/front-end, it looks like the function's being fed proper values. From agilfoy at frontiernet.net Thu Aug 28 17:49:18 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Thu, 28 Aug 2008 15:49:18 +0000 Subject: [Tutor] It works! (my booster pack generator) Message-ID: <20080828154918.lioqc5lpcgg4o4ws@webmail.frontiernet.net> The booster pack generator (my use of random.sample as described in a previous message) is working as intended now. There was a rather stupid typo in my code that was causing it to go wonky. Y'all still helped, though. A few people replied, but a bit of advice from: W W <srilyk at gmail.com> pointed me in the right direction. for card in random.sample(SpecialA, SA): print card he suggested changing to: print "Special: ", SpecialA, "\nSA: ", SA for card in random.sample(SpecialA, SA): print card Basically, what my program was doing: 1. Take a textfile, import it/convert it to a list via open("filename.txt).readlines() This list was defined as the variable "SpecialA_list". 2. Feed SpecialA_list, along with some other variables, into my function 3. "SpecialA" variable is set equal to a list consisting of items from "SpecialA_list" 4. Then sample from "SpecialA" & print the results. Thanks to the print statement that WW suggested, I figured out that the "SpecialA" variable was coming out as an empty list. [error in Step 3 of the above process list, so Step 4 had nothing to sample *from*, thus triggering the traceback]. I found the typo that was causing this, and fixed it. So, the SpecialA variable was set equal to the expected list, so random.sample could sample properly. Thank you. :) From kent37 at tds.net Thu Aug 28 18:11:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Aug 2008 12:11:24 -0400 Subject: [Tutor] It works! (my booster pack generator) In-Reply-To: <20080828154918.lioqc5lpcgg4o4ws@webmail.frontiernet.net> References: <20080828154918.lioqc5lpcgg4o4ws@webmail.frontiernet.net> Message-ID: <1c2a2c590808280911l6ac8b35ak2f7c6e8809d3735e@mail.gmail.com> On Thu, Aug 28, 2008 at 11:49 AM, Alan Gilfoy <agilfoy at frontiernet.net> wrote: > The booster pack generator (my use of random.sample as described in a > previous message) is working as intended now. > > There was a rather stupid typo in my code that was causing it to go wonky. > > Y'all still helped, though. A few people replied, but a bit of advice from: > W W <srilyk at gmail.com> pointed me in the right direction. As well as the lesson about using print statements to debug, I hope you have learned to believe the interpreters error messages. It usually knows what it is talking about :-) Kent From agilfoy at frontiernet.net Thu Aug 28 18:54:49 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Thu, 28 Aug 2008 16:54:49 +0000 Subject: [Tutor] It works! (my booster pack generator) In-Reply-To: <1c2a2c590808280911l6ac8b35ak2f7c6e8809d3735e@mail.gmail.com> References: <20080828154918.lioqc5lpcgg4o4ws@webmail.frontiernet.net> <1c2a2c590808280911l6ac8b35ak2f7c6e8809d3735e@mail.gmail.com> Message-ID: <20080828165449.gr69n96r4s8wc8o4@webmail.frontiernet.net> Yeah, I did a lot of python work for my high school's Senior Project (so, spring 2007); hadn't coded much since then, was rusty on the "pritn stattements for debugging" part. And I was trying to look at the code mentioned in the traceback, but due to my own mistake, I hadn't detected the problems with the lines that the traceback was pointing to. Quoting Kent Johnson <kent37 at tds.net>: > On Thu, Aug 28, 2008 at 11:49 AM, Alan Gilfoy > <agilfoy at frontiernet.net> wrote: >> The booster pack generator (my use of random.sample as described in a >> previous message) is working as intended now. >> >> There was a rather stupid typo in my code that was causing it to go wonky. >> >> Y'all still helped, though. A few people replied, but a bit of advice from: >> W W <srilyk at gmail.com> pointed me in the right direction. > > As well as the lesson about using print statements to debug, I hope > you have learned to believe the interpreters error messages. It > usually knows what it is talking about :-) > > Kent > From johanpo at googlemail.com Fri Aug 29 14:18:23 2008 From: johanpo at googlemail.com (johan nilsson) Date: Fri, 29 Aug 2008 14:18:23 +0200 Subject: [Tutor] Excel com strange behavior Message-ID: <4d7db9340808290518y6f2bb80ci651814f98effbffa@mail.gmail.com> Dear all, I have a problem with talking to Excel. Somehow the command Workbooks.Add() gives me problems? If I open a workbook in Excel, then I get the trace back below. I can not say that I quite understand why this does not work. Any insights would be highly appreciated. If I "manually" open the workbook, I can fill the data in the sheet Johan >>> from win32com.client import Dispatch >>> xlApp = Dispatch("Excel.Application") >>> xlApp.Visible = 1 >>> xlApp.Workbooks.Add() Traceback (most recent call last): File "<pyshell#67>", line 1, in <module> xlApp.Workbooks.Add() File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\dynamic.py", line 467, in __getattr__ if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\dynamic.py", line 295, in _make_method_ methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0) File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\build.py", line 297, in MakeFuncMethod return self.MakeDispatchFuncMethod(entry, name, bMakeClass) File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\build.py", line 318, in MakeDispatchFuncMethod s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):' File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\build.py", line 604, in BuildCallList argName = MakePublicAttributeName(argName) File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\build.py", line 542, in MakePublicAttributeName return filter( lambda char: char in valid_identifier_chars, className) File "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\build.py", line 542, in <lambda> return filter( lambda char: char in valid_identifier_chars, className) UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: ordinal not in range(128) >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/9a2dd971/attachment.htm> From kent37 at tds.net Fri Aug 29 14:47:07 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Aug 2008 08:47:07 -0400 Subject: [Tutor] Excel com strange behavior In-Reply-To: <4d7db9340808290518y6f2bb80ci651814f98effbffa@mail.gmail.com> References: <4d7db9340808290518y6f2bb80ci651814f98effbffa@mail.gmail.com> Message-ID: <1c2a2c590808290547r4f3a1069h655dff14dae09090@mail.gmail.com> On Fri, Aug 29, 2008 at 8:18 AM, johan nilsson <johanpo at googlemail.com> wrote: > "c:\pythonxy\python\lib\site-packages\pywin32-2.11-py2.5-win32.egg\win32com\client\build.py", > line 542, in <lambda> > return filter( lambda char: char in valid_identifier_chars, className) > UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: > ordinal not in range(128) I don't understand how your code is causing this error, but what it means is that some string that is expected to be ascii contains a non-ascii character with code 0x83. In Windows code page 1252 that is an ? character. Kent From etrade.griffiths at dsl.pipex.com Fri Aug 29 15:49:33 2008 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Fri, 29 Aug 2008 14:49:33 +0100 Subject: [Tutor] dynamic argument lists Message-ID: <72l93j$28cn2i@smtp.pipex.tiscali.co.uk> Hi I have a GUI program that extracts some information from the user as strings, and I then want to use the strings to form an argument list to another function. Hopefully the following code gives some flavour: def myfunc(**kwargs): while kwargs: name, value = kwargs.popitem() print name, value myfunc(a=1, b=2, c=3, d=4) arg_str = "a=1, b=2, c=3, d=4" myfunc(arg_str) ARG_STR will be built up from the data extracted from the GUI. I get this error TypeError: myfunc() takes exactly 0 arguments (1 given) I understand that ARG_STR is a string and that MYFUNC is expecting something else ,,, but not sure what it is. I have tried various dictionary configurations such as arg1 = ["a","b","c","d"] arg2 = [1,2,3,4] arg3 = dict(zip(arg1,arg2)) myfunc(arg3) but still get the same error message. All suggestions welcome! Thanks in advance Alun Griffiths From adrian.greyling at gmail.com Fri Aug 29 18:19:40 2008 From: adrian.greyling at gmail.com (Adrian Greyling) Date: Fri, 29 Aug 2008 12:19:40 -0400 Subject: [Tutor] Is this a "Class" problem? In-Reply-To: <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> References: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> Message-ID: <866c750d0808290919o64571516k89c95bf2b9c01cc@mail.gmail.com> Thanks for the response Jeff, although your answer has spawned another question or two! In your answer, you showed that the attribute " MySecondFrame.text_ctrl_2" doesn't exist and to correct that, you suggested the code below. (What I understand from your response is that I can't reference the original object, but I must create an instance of it. Is that right??) def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> m = MySecondFrame(self) m.Show() m.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' window") Here's where I get fuzzy... Let's say I've got a "frame_1" object that opens a new "frame_2" object. As you've suggested above, I'll use "m" to create an instance of a frame object. Now frame_2 opens a "dialog_1'" which asks for information that is sent back to 'frame_2'. How do I reference 'frame_2' in this case? Especially when frame_2 hasn't been closed and has just been waiting behind dialog_1 until dialog_1 closes. When I try to reference it again as "m = frame_2(self)" from a new function definition, aren't I creating a brand new frame_2 object that has "blank" attributes, so to speak? I'm sure I've made things clear as mud, but hopefully with my blathering, someone will undertand my utter confusion! Thanks everyone! Adrian On Mon, Aug 18, 2008 at 3:29 PM, Jeff Younker <jeff at drinktomi.com> wrote: > On Aug 18, 2008, at 9:13 AM, Adrian Greyling wrote: > > def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> > MySecondFrame(self).Show() > MySecondFrame.text_ctrl_2.SetValue("This text was generated from > the 'MainFrame' window") > > > The expression MySecondFrame(self) creates a new object. It > initializes the new object by calling the MySecondFrame's __init__ > method. > > class MySecondFrame(wx.Frame): > def __init__(self, *args, **kwds): > # begin wxGlade: MySecondFrame.__init__ > ... > > self.text_ctrl_2 = wx.TextCtrl(self, -1, "", > style=wx.TE_MULTILINE) > ... > > > > The __init__ method calls sets the variable text_ctrl_2 in the object > m. > > Your function MainToSecond is trying to get the attribute > MySecondFrame.text_ctrl_2. > This attribute does not exist. You want to get the attribute > m.text_ctrl_2. So, the method > should be: > > def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> > m = MySecondFrame(self) > m.Show() > m.text_ctrl_2.SetValue("This text was generated from the > 'MainFrame' window") > > > Also, method and function names should always start with a lower case > letter: always > mainToSecond and never MainToSecond > > -jeff > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/1321c4bc/attachment.htm> From kent37 at tds.net Fri Aug 29 18:20:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Aug 2008 12:20:18 -0400 Subject: [Tutor] dynamic argument lists In-Reply-To: <72l93j$28cn2i@smtp.pipex.tiscali.co.uk> References: <72l93j$28cn2i@smtp.pipex.tiscali.co.uk> Message-ID: <1c2a2c590808290920w1665bef7y23376f783a09c248@mail.gmail.com> On Fri, Aug 29, 2008 at 9:49 AM, eShopping <etrade.griffiths at dsl.pipex.com> wrote: > Hi > > I have a GUI program that extracts some information from the user as > strings, and I then want to use the strings to form an argument list to > another function. Hopefully the following code gives some flavour: > > def myfunc(**kwargs): > while kwargs: > name, value = kwargs.popitem() > print name, value > > myfunc(a=1, b=2, c=3, d=4) > arg_str = "a=1, b=2, c=3, d=4" > myfunc(arg_str) > > ARG_STR will be built up from the data extracted from the GUI. I get this > error > > TypeError: myfunc() takes exactly 0 arguments (1 given) > > I understand that ARG_STR is a string and that MYFUNC is expecting something > else ,,, but not sure what it is. I have tried various dictionary > configurations such as > > arg1 = ["a","b","c","d"] > arg2 = [1,2,3,4] > arg3 = dict(zip(arg1,arg2)) > myfunc(arg3) If you want to pass a dict containing the keywords, rather than actual keywords, the syntax is myfunc(**arg3) It parallels the syntax used to define myfunc(). Kent From bgailer at gmail.com Fri Aug 29 19:02:12 2008 From: bgailer at gmail.com (Bob Gailer) Date: Fri, 29 Aug 2008 13:02:12 -0400 Subject: [Tutor] dynamic argument lists In-Reply-To: <1c2a2c590808290920w1665bef7y23376f783a09c248@mail.gmail.com> References: <72l93j$28cn2i@smtp.pipex.tiscali.co.uk> <1c2a2c590808290920w1665bef7y23376f783a09c248@mail.gmail.com> Message-ID: <23d7abd0808291002x4e4a04ap54adca22b3246db3@mail.gmail.com> On Fri, Aug 29, 2008 at 12:20 PM, Kent Johnson <kent37 at tds.net> wrote: > On Fri, Aug 29, 2008 at 9:49 AM, eShopping > <etrade.griffiths at dsl.pipex.com> wrote: > > Hi > > > > I have a GUI program that extracts some information from the user as > > strings, and I then want to use the strings to form an argument list to > > another function. Hopefully the following code gives some flavour: > > > > def myfunc(**kwargs): > > while kwargs: > > name, value = kwargs.popitem() > > print name, value > > > > myfunc(a=1, b=2, c=3, d=4) > > arg_str = "a=1, b=2, c=3, d=4" > > myfunc(arg_str) > > > > ARG_STR will be built up from the data extracted from the GUI. I get > this > > error > > > > TypeError: myfunc() takes exactly 0 arguments (1 given) > > > > I understand that ARG_STR is a string and that MYFUNC is expecting > something > > else ,,, but not sure what it is. I have tried various dictionary > > configurations such as > > > > arg1 = ["a","b","c","d"] > > arg2 = [1,2,3,4] > > arg3 = dict(zip(arg1,arg2)) > > myfunc(arg3) > myfunc(**arg3) Let's back up to arg_str = "a=1, b=2, c=3, d=4" To create a dictionary from that: argDict = dict(pair.split('=') for pair in arg_str.split(',')) If there is no compelling requirement that myfunc's argument be in the form **kwargs then def myfunc(kwargs): while kwargs: name, value = kwargs.popitem() print name, value myfunc(argDict) -- Bob Gailer 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/9ed3dc21/attachment-0001.htm> From bgailer at gmail.com Fri Aug 29 19:02:12 2008 From: bgailer at gmail.com (Bob Gailer) Date: Fri, 29 Aug 2008 13:02:12 -0400 Subject: [Tutor] dynamic argument lists In-Reply-To: <1c2a2c590808290920w1665bef7y23376f783a09c248@mail.gmail.com> References: <72l93j$28cn2i@smtp.pipex.tiscali.co.uk> <1c2a2c590808290920w1665bef7y23376f783a09c248@mail.gmail.com> Message-ID: <23d7abd0808291002x4e4a04ap54adca22b3246db3@mail.gmail.com> On Fri, Aug 29, 2008 at 12:20 PM, Kent Johnson <kent37 at tds.net> wrote: > On Fri, Aug 29, 2008 at 9:49 AM, eShopping > <etrade.griffiths at dsl.pipex.com> wrote: > > Hi > > > > I have a GUI program that extracts some information from the user as > > strings, and I then want to use the strings to form an argument list to > > another function. Hopefully the following code gives some flavour: > > > > def myfunc(**kwargs): > > while kwargs: > > name, value = kwargs.popitem() > > print name, value > > > > myfunc(a=1, b=2, c=3, d=4) > > arg_str = "a=1, b=2, c=3, d=4" > > myfunc(arg_str) > > > > ARG_STR will be built up from the data extracted from the GUI. I get > this > > error > > > > TypeError: myfunc() takes exactly 0 arguments (1 given) > > > > I understand that ARG_STR is a string and that MYFUNC is expecting > something > > else ,,, but not sure what it is. I have tried various dictionary > > configurations such as > > > > arg1 = ["a","b","c","d"] > > arg2 = [1,2,3,4] > > arg3 = dict(zip(arg1,arg2)) > > myfunc(arg3) > myfunc(**arg3) Let's back up to arg_str = "a=1, b=2, c=3, d=4" To create a dictionary from that: argDict = dict(pair.split('=') for pair in arg_str.split(',')) If there is no compelling requirement that myfunc's argument be in the form **kwargs then def myfunc(kwargs): while kwargs: name, value = kwargs.popitem() print name, value myfunc(argDict) -- Bob Gailer 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/9ed3dc21/attachment-0002.htm> From timothy.grant at gmail.com Fri Aug 29 22:42:47 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Fri, 29 Aug 2008 13:42:47 -0700 Subject: [Tutor] Is this a "Class" problem? In-Reply-To: <866c750d0808290919o64571516k89c95bf2b9c01cc@mail.gmail.com> References: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> <866c750d0808290919o64571516k89c95bf2b9c01cc@mail.gmail.com> Message-ID: <e775286d0808291342t6e623f38me581256fc1e8b293@mail.gmail.com> On Fri, Aug 29, 2008 at 9:19 AM, Adrian Greyling <adrian.greyling at gmail.com> wrote: > Thanks for the response Jeff, although your answer has spawned another > question or two! In your answer, you showed that the attribute " > MySecondFrame.text_ctrl_2" doesn't exist and to correct that, you suggested > the code below. (What I understand from your response is that I can't > reference the original object, but I must create an instance of it. Is that > right??) > > def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> > > m = MySecondFrame(self) > m.Show() > > m.text_ctrl_2.SetValue("This text was generated from the 'MainFrame' > window") > > Here's where I get fuzzy... Let's say I've got a "frame_1" object > that opens a new "frame_2" object. As you've suggested above, I'll use "m" > to create an instance of a frame object. Now frame_2 opens a "dialog_1'" > which asks for information that is sent back to 'frame_2'. How do I > reference 'frame_2' in this case? Especially when frame_2 hasn't been > closed and has just been waiting behind dialog_1 until dialog_1 closes. > When I try to reference it again as "m = frame_2(self)" from a new function > definition, aren't I creating a brand new frame_2 object that has "blank" > attributes, so to speak? > > I'm sure I've made things clear as mud, but hopefully with my blathering, > someone will undertand my utter confusion! > > Thanks everyone! > Adrian > > > > > On Mon, Aug 18, 2008 at 3:29 PM, Jeff Younker <jeff at drinktomi.com> wrote: >> >> On Aug 18, 2008, at 9:13 AM, Adrian Greyling wrote: >> >> def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> >> MySecondFrame(self).Show() >> MySecondFrame.text_ctrl_2.SetValue("This text was generated from >> the 'MainFrame' window") >> >> The expression MySecondFrame(self) creates a new object. It >> initializes the new object by calling the MySecondFrame's __init__ >> method. >> >> class MySecondFrame(wx.Frame): >> def __init__(self, *args, **kwds): >> # begin wxGlade: MySecondFrame.__init__ >> ... >> >> self.text_ctrl_2 = wx.TextCtrl(self, -1, "", >> style=wx.TE_MULTILINE) >> ... >> >> The __init__ method calls sets the variable text_ctrl_2 in the object >> m. >> Your function MainToSecond is trying to get the attribute >> MySecondFrame.text_ctrl_2. >> This attribute does not exist. You want to get the attribute >> m.text_ctrl_2. So, the method >> should be: >> def MainToSecond(self, event): # wxGlade: MyMainFrame.<event_handler> >> m = MySecondFrame(self) >> m.Show() >> m.text_ctrl_2.SetValue("This text was generated from the >> 'MainFrame' window") >> >> Also, method and function names should always start with a lower case >> letter: always >> mainToSecond and never MainToSecond >> -jeff > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Adrian, Two things... You should check out the wxpython mailing list. It's a much better place to ask wxPython related questions. You should check out the wx.lib.pubsub module. It will allow you to publish data in one object and subscribe to it in another. -- Stand Fast, tjg. [Timothy Grant] From ceasar102 at yahoo.com Fri Aug 29 23:13:04 2008 From: ceasar102 at yahoo.com (ammar azif) Date: Fri, 29 Aug 2008 14:13:04 -0700 (PDT) Subject: [Tutor] Puzzled Message-ID: <779022.9469.qm@web56813.mail.re3.yahoo.com> I wrote a python program that used time() function from the time module to retrieve time in seconds since Epoch. After the value was retrieved which I checked is a float by using type(),? the value was then written into a file in binary format. Then another C program that I wrote opened the file and converted the value into a time_t variable but it was totally different from the correct value. Then I found that the time_t size is actually 4 byte integer which is not the same with 8-byte float value returned by time.time(). Why is this so? Being written with C library, isn't python suppose to work well with it? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/430724d5/attachment.htm> From kent37 at tds.net Fri Aug 29 23:31:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Aug 2008 17:31:29 -0400 Subject: [Tutor] Is this a "Class" problem? In-Reply-To: <866c750d0808290919o64571516k89c95bf2b9c01cc@mail.gmail.com> References: <866c750d0808180913g29a3e83bocfa36c6448235024@mail.gmail.com> <5452EC5C-254A-4FA5-B749-6B6A8E073191@drinktomi.com> <866c750d0808290919o64571516k89c95bf2b9c01cc@mail.gmail.com> Message-ID: <1c2a2c590808291431h2887b538pb50e4cc1b3ef975d@mail.gmail.com> On Fri, Aug 29, 2008 at 12:19 PM, Adrian Greyling <adrian.greyling at gmail.com> wrote: > Here's where I get fuzzy... Let's say I've got a "frame_1" object > that opens a new "frame_2" object. As you've suggested above, I'll use "m" > to create an instance of a frame object. Now frame_2 opens a "dialog_1'" > which asks for information that is sent back to 'frame_2'. How do I > reference 'frame_2' in this case? Especially when frame_2 hasn't been > closed and has just been waiting behind dialog_1 until dialog_1 closes. > When I try to reference it again as "m = frame_2(self)" from a new function > definition, aren't I creating a brand new frame_2 object that has "blank" > attributes, so to speak? Generally the way this works is something like: - frame 2 creates dialog box - frame 2 shows dialog box and waits for the dialog box to be dismissed - frame 2 gets result from dialog box There are several examples of this in the wx demo, see MultiChoiceDialog, SingleChoiceDialog, TextEntryDialog. If you are writing your own custom dialog, make a method that allows the client code to retrieve the user data from it. Kent From kent37 at tds.net Fri Aug 29 23:41:15 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Aug 2008 17:41:15 -0400 Subject: [Tutor] Puzzled In-Reply-To: <779022.9469.qm@web56813.mail.re3.yahoo.com> References: <779022.9469.qm@web56813.mail.re3.yahoo.com> Message-ID: <1c2a2c590808291441y243e30bar7f6eeca04cc342d1@mail.gmail.com> On Fri, Aug 29, 2008 at 5:13 PM, ammar azif <ceasar102 at yahoo.com> wrote: > I wrote a python program that used time() function from the time module to > retrieve time in seconds since Epoch. After the value was retrieved which I > checked is a float by using type(), the value was then written into a file > in binary format. Then another C program that I wrote opened the file and > converted the value into a time_t variable but it was totally different from > the correct value. Then I found that the time_t size is actually 4 byte > integer which is not the same with 8-byte float value returned by > time.time(). Why is this so? Being written with C library, isn't python > suppose to work well with it? The C time_t type is very loosely specified; in ANSI C it is only required to be an arithmetic type. According to Wikipedia (http://en.wikipedia.org/wiki/Time_t), Posix-compliant systems still have latitude to implement it as 32 or 64 bits. Python tries to be bit higher level, giving you fractional seconds if the implementation supports it and a common data type across implementations. So there is not an exact match in functionality. If you want to write data to file in a format that can be read by another program, you should look at the struct module. Kent From ceasar102 at yahoo.com Sat Aug 30 00:15:19 2008 From: ceasar102 at yahoo.com (ammar azif) Date: Fri, 29 Aug 2008 15:15:19 -0700 (PDT) Subject: [Tutor] Puzzled In-Reply-To: <1c2a2c590808291441y243e30bar7f6eeca04cc342d1@mail.gmail.com> Message-ID: <900301.50904.qm@web56813.mail.re3.yahoo.com> Thanks for the explanation. Btw, How can I get the size of python primitive data types in bytes? Is it defined somewhere in a file that I can look at? --- On Fri, 8/29/08, Kent Johnson <kent37 at tds.net> wrote: From: Kent Johnson <kent37 at tds.net> Subject: Re: [Tutor] Puzzled To: ceasar102 at yahoo.com Cc: tutor at python.org Date: Friday, August 29, 2008, 4:41 PM On Fri, Aug 29, 2008 at 5:13 PM, ammar azif <ceasar102 at yahoo.com> wrote: > I wrote a python program that used time() function from the time module to > retrieve time in seconds since Epoch. After the value was retrieved which I > checked is a float by using type(), the value was then written into a file > in binary format. Then another C program that I wrote opened the file and > converted the value into a time_t variable but it was totally different from > the correct value. Then I found that the time_t size is actually 4 byte > integer which is not the same with 8-byte float value returned by > time.time(). Why is this so? Being written with C library, isn't python > suppose to work well with it? The C time_t type is very loosely specified; in ANSI C it is only required to be an arithmetic type. According to Wikipedia (http://en.wikipedia.org/wiki/Time_t), Posix-compliant systems still have latitude to implement it as 32 or 64 bits. Python tries to be bit higher level, giving you fractional seconds if the implementation supports it and a common data type across implementations. So there is not an exact match in functionality. If you want to write data to file in a format that can be read by another program, you should look at the struct module. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20080829/2594970d/attachment-0001.htm> From kent37 at tds.net Sat Aug 30 02:47:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Aug 2008 20:47:11 -0400 Subject: [Tutor] Puzzled In-Reply-To: <900301.50904.qm@web56813.mail.re3.yahoo.com> References: <1c2a2c590808291441y243e30bar7f6eeca04cc342d1@mail.gmail.com> <900301.50904.qm@web56813.mail.re3.yahoo.com> Message-ID: <1c2a2c590808291747h7dddb959p455f2b04a722a028@mail.gmail.com> On Fri, Aug 29, 2008 at 6:15 PM, ammar azif <ceasar102 at yahoo.com> wrote: > Thanks for the explanation. Btw, How can I get the size of python primitive > data types in bytes? Is it defined somewhere in a file that I can look at? Not really. sys.maxint gives the largest int, from which you can infer the size. Here is a (complex) recipe that reports sizes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/546530 Kent From etrade.griffiths at dsl.pipex.com Sat Aug 30 11:09:36 2008 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Sat, 30 Aug 2008 10:09:36 +0100 Subject: [Tutor] dynamic argument lists In-Reply-To: <mailman.1889.1220048133.3486.tutor@python.org> References: <mailman.1889.1220048133.3486.tutor@python.org> Message-ID: <72l93j$28l2h8@smtp.pipex.tiscali.co.uk> Bob, Kent thanks for the suggestions. Bob made the comment "If there is no compelling requirement that myfunc's argument be in the form **kwargs ...", but I'm afraid I don't understand the difference between myfunc (**kwargs) and myfunc (kwargs) Would someone mind explaining this? I never managed to find a satisfactory explanation for what "**" means! Alun Griffiths > <etrade.griffiths at dsl.pipex.com> wrote: > > > Hi > > > > > > I have a GUI program that extracts some information from the user as > > > strings, and I then want to use the strings to form an argument list to > > > another function. Hopefully the following code gives some flavour: > > > > > > def myfunc(**kwargs): > > > while kwargs: > > > name, value = kwargs.popitem() > > > print name, value > > > > > > myfunc(a=1, b=2, c=3, d=4) > > > arg_str = "a=1, b=2, c=3, d=4" > > > myfunc(arg_str) > > > > > > ARG_STR will be built up from the data extracted from the GUI. I get > > this > > > error > > > > > > TypeError: myfunc() takes exactly 0 arguments (1 given) > > > > > > I understand that ARG_STR is a string and that MYFUNC is expecting > > something > > > else ,,, but not sure what it is. I have tried various dictionary > > > configurations such as > > > > > > arg1 = ["a","b","c","d"] > > > arg2 = [1,2,3,4] > > > arg3 = dict(zip(arg1,arg2)) > > > myfunc(arg3) > > > > myfunc(**arg3) > >Let's back up to arg_str = "a=1, b=2, c=3, d=4" > >To create a dictionary from that: > >argDict = dict(pair.split('=') for pair in arg_str.split(',')) > >If there is no compelling requirement that myfunc's argument be in the form >**kwargs then > >def myfunc(kwargs): > while kwargs: > name, value = kwargs.popitem() > print name, value > >myfunc(argDict) From kent37 at tds.net Sat Aug 30 13:59:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Aug 2008 07:59:27 -0400 Subject: [Tutor] dynamic argument lists In-Reply-To: <72l93j$28l2h8@smtp.pipex.tiscali.co.uk> References: <mailman.1889.1220048133.3486.tutor@python.org> <72l93j$28l2h8@smtp.pipex.tiscali.co.uk> Message-ID: <1c2a2c590808300459v2aed7377gad4305702cc05b3@mail.gmail.com> On Sat, Aug 30, 2008 at 5:09 AM, eShopping <etrade.griffiths at dsl.pipex.com> wrote: > I don't understand the difference between > > myfunc (**kwargs) > > and > > myfunc (kwargs) > > Would someone mind explaining this? I never managed to find a satisfactory > explanation for what "**" means! One is a function that takes keyword args, with the keyword args being passed in a dict; the other is a function that just takes a dict as an argument. For example, here f() is a function of a single argument.: In [18]: def f(x): ....: print x The argument can be a string: In [19]: f('foo') foo Or a dict: In [20]: d=dict(a=1, b=2) In [21]: f(d) {'a': 1, 'b': 2} f() doesn't take keyword arguments: In [27]: f(a=1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/kent/<ipython console> in <module>() TypeError: f() got an unexpected keyword argument 'a' The ** notation means, pass the key/value pairs of the dict as keyword args. Since f() doesn't accept keyword args, it fails the same way as an explicit keyword: In [22]: f(**d) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/kent/<ipython console> in <module>() TypeError: f() got an unexpected keyword argument 'a' Here is a function that takes keyword args: In [23]: def g(a=None, b=None): ....: print a, b In [24]: g('foo') foo None Passing the dict without ** treats it as an ordinary argument. Here the parameter 'a' is set to the dict; 'b' is None: In [25]: g(d) {'a': 1, 'b': 2} None Using the ** syntax assigns the key/value pairs of the dict to the keyword args of the function: In [26]: g(**d) 1 2 The names of the keywords are still checked: In [28]: d['c'] = 3 In [29]: g(**d) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/kent/<ipython console> in <module>() TypeError: g() got an unexpected keyword argument 'c' You can define a function that accepts any keywords. This is the flip side of passing keywords in a dict; the function receives a dict containing the keywords: In [30]: def h(**kwargs): ....: print kwargs This particular function takes *only* keyword arguments: In [31]: h(1) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/kent/<ipython console> in <module>() TypeError: h() takes exactly 0 arguments (1 given) It accepts any keyword arguments. They appear in a dict named kwargs: In [32]: h(a=1, b=2) {'a': 1, 'b': 2} Passing a dict directly doesnt' work: In [33]: h(d) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/kent/<ipython console> in <module>() TypeError: h() takes exactly 0 arguments (1 given) Using the ** syntax in the call works: In [34]: h(**d) {'a': 1, 'c': 3, 'b': 2} There is also a similar * syntax for positional paramaters, and you can use any combination of named positional, named keyword, * and ** args in the same function. See http://docs.python.org/tut/node6.html#SECTION006700000000000000000 http://docs.python.org/ref/function.html http://docs.python.org/ref/calls.html#calls for more. Kent From bgailer at gmail.com Sat Aug 30 15:16:56 2008 From: bgailer at gmail.com (bob gailer) Date: Sat, 30 Aug 2008 09:16:56 -0400 Subject: [Tutor] dynamic argument lists In-Reply-To: <72l93j$28l2h8@smtp.pipex.tiscali.co.uk> References: <mailman.1889.1220048133.3486.tutor@python.org> <72l93j$28l2h8@smtp.pipex.tiscali.co.uk> Message-ID: <48B94848.800@gmail.com> eShopping wrote: > Bob, Kent > > thanks for the suggestions. Bob made the comment "If there is no > compelling requirement that myfunc's argument be in the form **kwargs > ...", but I'm afraid I don't understand the difference between > > myfunc (**kwargs) > > and > > myfunc (kwargs) > > Would someone mind explaining this? I never managed to find a > satisfactory explanation for what "**" means! > Did you RTFM under 7.6 Function definitions? If so how did it fail to help? "If the form ``|*identifier|'' is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form ``|**identifier|'' is present, it is initialized to a new dictionary receiving any excess keyword arguments." -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From lie.1296 at gmail.com Sat Aug 30 19:39:45 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 31 Aug 2008 00:39:45 +0700 Subject: [Tutor] dynamic argument lists In-Reply-To: <mailman.59.1220090417.13498.tutor@python.org> References: <mailman.59.1220090417.13498.tutor@python.org> Message-ID: <1220117986.6470.33.camel@lieryan-laptop> On Sat, 2008-08-30 at 12:00 +0200, tutor-request at python.org wrote: > > Message: 2 > Date: Sat, 30 Aug 2008 10:09:36 +0100 > From: eShopping <etrade.griffiths at dsl.pipex.com> > Subject: Re: [Tutor] dynamic argument lists > To: tutor at python.org > Message-ID: <72l93j$28l2h8 at smtp.pipex.tiscali.co.uk> > Content-Type: text/plain; charset=us-ascii; format=flowed; > x-avg-checked=avg-ok-571D6DEA > > Bob, Kent > > thanks for the suggestions. Bob made the comment "If there is no > compelling requirement that myfunc's argument be in the form **kwargs > ...", but I'm afraid I don't understand the difference between > > myfunc (**kwargs) > > and > > myfunc (kwargs) > > Would someone mind explaining this? I never managed to find a > satisfactory explanation for what "**" means! First you have to understand what ** in a function definition means: def func(positionalArg, *excessPositionalArg, **excessNamedArg): ... positionalArg is the regular arguments you use, it is accessible by placing arguments at their respective position and the name it is assigned to, e.g. def func1(arg1, arg2, arg3): print arg1, arg2, arg3 func1(1, 2, 3) # 1 2 3 func1(1, 2, 3, 4) # Wrong number of argument Error func1(1, arg3 = 2, arg2 = 3) # 1 3 2 excessPositionalArg is a list of positional arguments that doesn't fit in the regular positional argument, e.g. def func2(arg1, arg2, *epa): for arg in epa: print arg, func2(1, 2, 3, 4, 5, 6, 7) # 3 4 5 6 7 last, is excessNamedArg. As we have learned, there are two ways to access an argument, by its position and by its names, excessNamedArgument is a dictionary containing the named arguments that aren't explicitly specified in the function definition, e.g. def func3(arg1, arg2, *args, **kargs): print arg1, arg2, for arg in args: print '[1 -- %s]' % arg, for key, value in kargs: print '[2 -- %s: %s]' % (key, value) func3(1, 2, otherargs = 10): # 1 2 [2 -- otherargs: 10] func3(1, arg2 = 2, otherargs1 = 10, otherargs2 = 20) # 1 2 [2 -- otherargs1: 10] # [2 -- otherargs2: 20] Now, to the question, then what is this: d = {'a':10, 'b':20, arg2: 30} func3(1, **d) # 1 30 [2 -- a: 10] # [2 -- b: 20] compare: func3(1, 2, d) # 1 2 [1 -- {'a':10, 'b':20, arg2: 30}] If you called it like func3(1, 2, **d), and d is a dictionary, then d would be expanded and its key/value pair be considered as named arguments to the function. OTOH, func3(1, 2, d) would pass the whole dictionary to func3. Since in this case, we have declared a container for excessPositionalArgument, d is treated as excessPositionalArgument, if we haven't done that, an bad number of argument error would occur because there is no more positional argument left. From Jaggojaggo+Py at gmail.com Sun Aug 31 11:38:45 2008 From: Jaggojaggo+Py at gmail.com (OmerT) Date: Sun, 31 Aug 2008 12:38:45 +0300 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> Message-ID: <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> I'm unfamiliar with the random.sample function, yet I can't help but wonder: Do you ever got the same card twice? Is that intentional ? On Thu, Aug 28, 2008 at 6:29 PM, Alan Gilfoy <agilfoy at frontiernet.net> wrote: > Quoting W W <srilyk at gmail.com>: > > >>> The number of items I want from a list is smaller than the population >>> (number of items) in the list, so it should work. >>> >>> In this specific case, I'm asking for one item from a five-item list. >> >> Are you sure? >> >> change this: >> for card in random.sample(SpecialA, SA): >> >> to this: >> >> print "Special: ", SpecialA, "\nSA: ", SA >> for card in random.sample(SpecialA, SA): >> >> then give us the output. I'll bet that your SA value is never reset to 1. >> > There is a part of my front-end code that declares the SA variable as equal > to 1 for the card set in question, and feeds that into the processing > function. > Changing the block of code, as you suggest, still gets me a traceback: > > Special: [] > SA: 1 > > Traceback (most recent call last): > File "C:\Documents and Settings\Alan\My > Documents\_Alan_Programming\trunk\BoosterPackMaker\BoosterPackMaker.py", > line 104, in <module> > SixList_PackChooser(C_list, UC_list, R_list, BL_list, SpecialA_list, > SpecialB_list, C, UC, R, BL, SA, SB) > File "C:\Documents and Settings\Alan\My > Documents\_Alan_Programming\trunk\BoosterPackMaker\PackGenerator.py", line > 367, in SixList_PackChooser > for card in random.sample(SpecialA, SA): > File "C:\Python25\lib\random.py", line 303, in sample > raise ValueError, "sample larger than population" > ValueError: sample larger than population > > So, I'm asking my program to pick 1 item from a 0-item list. How there are > zero items in the list, I don't know. That must be the problem. > >> >> You've obviously researched enough to know this: >>>>> >>>>> mylist = [1, 2, 3, 4, 5] >>>>> from random import sample >>>>> sample(mylist, 3) >> >> [2, 1, 4] >>>>> >>>>> sample(mylist, 10) >> >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> File "/usr/lib/python2.5/random.py", line 303, in sample >> raise ValueError, "sample larger than population" >> ValueError: sample larger than population >> > Okay, asking for 3 items from a 5-item list works, and asking for 10 items > from a 5-item list doesn't work. It should be trying to pick 1 item from the > 5-item SpecialA list, but somehow the SpecialA list has zero items in it. >> >> So give the print statement before your for loop a try and see what you >> come >> up with. > > Okay, I cut'n'pasted it before the traceback message. >> >> HTH, >> Wayne > > Thank you. > ----------------------------------------------- > SixList_PackChooser(C_list, UC_list, R_list, BL_list, SpecialA_list, > SpecialB_list, C, UC, R, BL, SA, SB) > > ^ The error occurs in this function. > The program picks C number of items from C_list and displays them just fine. > The program picks UC number of items from UC_list and displays them just > fine. > The program picks R number of items from R_list and displays them just fine. > The program picks BL number of items from BL_list and displays them just > fine. > > Looking at my user-interface/front-end, it looks like the function's being > fed proper values. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Sun Aug 31 15:00:06 2008 From: bgailer at gmail.com (bob gailer) Date: Sun, 31 Aug 2008 09:00:06 -0400 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> Message-ID: <48BA95D6.6020007@gmail.com> OmerT wrote: > I'm unfamiliar with the random.sample function, yet I can't help but wonder: > Do you ever got the same card twice? > Quoting the manual: sample( population, k) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? From Jaggojaggo+Py at gmail.com Sun Aug 31 16:25:29 2008 From: Jaggojaggo+Py at gmail.com (OmerT) Date: Sun, 31 Aug 2008 17:25:29 +0300 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <48BA95D6.6020007@gmail.com> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> <48BA95D6.6020007@gmail.com> Message-ID: <515008f10808310725x26b5eed8jce7345977d0c8dfb@mail.gmail.com> Bob, Kent, I understood all that from the context and yet do not feel familiar enough with the information nor had the time to lookup. The point I'm making is that Alan has a logical problem with his generator regarding the question of repetitive cards in a booster: On one hand, the script does not allow to repeat cards. On the other- he tries to display 8 cards out of a 5 card pool, which is impossible without repeating cards. That's all.. On Sun, Aug 31, 2008 at 4:00 PM, bob gailer <bgailer at gmail.com> wrote: > OmerT wrote: >> >> I'm unfamiliar with the random.sample function, yet I can't help but >> wonder: >> Do you ever got the same card twice? >> > > Quoting the manual: > > sample( population, k) > Return a k length list of unique elements chosen from the population > sequence. Used for random sampling without replacement. > > -- > Bob Gailer > Chapel Hill NC 919-636-4239 > > When we take the time to be aware of our feelings and needs we have more > satisfying interatctions with others. > > Nonviolent Communication provides tools for this awareness. > > As a coach and trainer I can assist you in learning this process. > > What is YOUR biggest relationship challenge? > > From agilfoy at frontiernet.net Sun Aug 31 18:09:31 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sun, 31 Aug 2008 16:09:31 +0000 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> Message-ID: <20080831160931.u2sxj3fi68okk0sw@webmail.frontiernet.net> I shouldn't get the same card twice in the same batch, no. Of course, in separate trials, I may get the same card again. Basically, I type the names of relevant cards in a list, and proceed to "tell" my program which list to read, and how many cards to pick from that list. Normally, I put each card name in the list only once. But if I type the same card name twice, the program sees the repetitions as different entities, and may display both of 'em if the randomness works out that way. random.sample I think runs dependent trials (the first pick affects the odds of the second pick, etc.) - kind of like pulling tickets from a hat. This is as opposed to independent random trials a la dice rolling. Someone correct me if I'm wrong on this - for this application, I want dependent trials. Quoting OmerT <Jaggojaggo+Py at gmail.com>: > I'm unfamiliar with the random.sample function, yet I can't help but wonder: > Do you ever got the same card twice? > Is that intentional ? From agilfoy at frontiernet.net Sun Aug 31 18:24:26 2008 From: agilfoy at frontiernet.net (Alan Gilfoy) Date: Sun, 31 Aug 2008 16:24:26 +0000 Subject: [Tutor] Having trouble with a component of the random module In-Reply-To: <515008f10808310725x26b5eed8jce7345977d0c8dfb@mail.gmail.com> References: <20080828063319.fpoi5r9gnk8048sw@webmail.frontiernet.net> <333efb450808280244o28ad0932i2df091839363f805@mail.gmail.com> <20080828152917.tthjkntkgs0w0cc4@webmail.frontiernet.net> <515008f10808310238x2710d53p9043efbf2f450581@mail.gmail.com> <48BA95D6.6020007@gmail.com> <515008f10808310725x26b5eed8jce7345977d0c8dfb@mail.gmail.com> Message-ID: <20080831162426.rhg56yaw748skkgw@webmail.frontiernet.net> In this case, I was trying to pull 1 card from a 5-card pool, which should have worked. There was a typo in my code that I have since fixed, and it is working. I have to make sure manually that I'm not telling the program to pick more cards than exist in the list. I can do this two ways: Make the list long enough, and tell the selector function to pick a small enough amount from that pool. The following is not related to my code per se, but rather to an aspect of MTG booster packs that I have successfully replicated: In most cases, every common appears at the same frequency as every other common, so I normally put each name on the commons list exactly once. (and so on for other lists/other rarity levels) Thus, each card will be displayed only once per pack, unless I repeat the same name in the source list multiple times. (The program sees those repetitions as different entities.) Quoting OmerT <Jaggojaggo+Py at gmail.com>: > Bob, Kent, > > I understood all that from the context and yet do not feel familiar > enough with the information nor had the time to lookup. > > The point I'm making is that Alan has a logical problem with his > generator regarding the question of repetitive cards in a booster: > On one hand, the script does not allow to repeat cards. On the other- > he tries to display 8 cards out of a 5 card pool, which is impossible > without repeating cards. > > That's all.. > > On Sun, Aug 31, 2008 at 4:00 PM, bob gailer <bgailer at gmail.com> wrote: >> OmerT wrote: >>> >>> I'm unfamiliar with the random.sample function, yet I can't help but >>> wonder: >>> Do you ever got the same card twice? >>> >> >> Quoting the manual: >> >> sample( population, k) >> Return a k length list of unique elements chosen from the population >> sequence. Used for random sampling without replacement. >> >> -- >> Bob Gailer >> Chapel Hill NC 919-636-4239 >> >> When we take the time to be aware of our feelings and needs we have more >> satisfying interatctions with others. >> >> Nonviolent Communication provides tools for this awareness. >> >> As a coach and trainer I can assist you in learning this process. >> >> What is YOUR biggest relationship challenge? >> >> >